GOOGLE ADS

viernes, 22 de abril de 2022

¿Cuál es la forma más bonita de comparar un valor con varios valores? [duplicar]

Esta pregunta ya tiene respuestas aquí:


Solución del problema

Lo que suelo hacer es poner esos valores múltiples en una matriz como

var options = [foo, bar];

y luego, use indexOf()

if(options.indexOf(foobar) > -1){
//do something
}

por belleza:

if([foo, bar].indexOf(foobar) +1){
//you can't get any more pretty than this:)
}

y para los navegadores más antiguos:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )

if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n!= n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n!= 0 && n!= Infinity && n!= -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0? n: Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}

No hay comentarios.:

Publicar un comentario

Flutter: error de rango al acceder a la respuesta JSON

Estoy accediendo a una respuesta JSON con la siguiente estructura. { "fullName": "FirstName LastName", "listings...