是否有更简单的方法来确定变量是否等于某个范围的值,例如:
if x === 5 || 6
而不是像这样的钝器:
if x === 5 || x === 6
?
是否有更简单的方法来确定变量是否等于某个范围的值,例如:
if x === 5 || 6
而不是像这样的钝器:
if x === 5 || x === 6
?
您可以将值存储在数组中,并使用以下命令检查变量是否存在于数组中[].indexOf
:
if([5, 6].indexOf(x) > -1) {
// ...
}
如果-1
返回,则该变量不存在于数组中。
取决于您正在执行的测试类型。如果你有静态字符串,这很容易通过正则表达式检查:
if (/^[56ab]$/.test(item)) {
//-or-
if (/^(foo|bar|baz|fizz|buzz)$/.test(item)) {
doStuff();
} else {
doOtherStuff();
}
如果您有一小组值(字符串或数字),则可以使用switch
:
switch (item) {
case 1:
case 2:
case 3:
doStuff();
break;
default:
doOtherStuff();
break;
}
如果您有很长的值列表,您可能应该使用带有~arr.indexOf(item)
, 或的数组arr.contains(item)
:
vals = [1,3,18,3902,...];
if (~vals.indexOf(item)) {
doStuff();
} else {
doOtherStuff();
}
不幸的Array.prototype.indexOf
是,某些浏览器不支持。幸运的是,有一个 polyfill 可用。如果您正在经历 polyfilling 的麻烦Array.prototype.indexOf
,您不妨添加Array.prototype.contains
.
根据您关联数据的方式,您可以在对象中存储一个动态字符串列表作为其他相关信息的映射:
var map = {
foo: bar,
fizz: buzz
}
if (item in map) {
//-or-
if (map.hasOwnProperty(item)) {
doStuff(map[item]);
} else {
doOtherStuff();
}
in
将检查整个原型链而Object.prototype.hasOwnProperty
只会检查对象,因此请注意它们是不同的。
完全没问题。如果您有更长的值列表,也许您可以使用以下内容:
if ([5,6,7,8].indexOf(x) > -1) {
}
是的。您可以使用自己的功能。此示例使用.some
:
var foo = [ 5, 6 ].some(function(val) {
return val === x;
});
foo; // true
这是我决定使用的:
Object.prototype.isin = function() {
for(var i = arguments.length; i--;) {
var a = arguments[i];
if(a.constructor === Array) {
for(var j = a.length; j--;)
if(a[j] == this) return true;
}
else if(a == this) return true;
}
return false;
}
你会像这样使用它:
var fav = 'pear',
fruit = ['apple', 'banana', 'orange', 'pear'],
plu = [4152, 4231, 3030, 4409];
if (fav.isin(fruit, plu, 'eggs', 'cheese')) {
//do something cool
}
优点是:
如果您不想允许类型强制(indexOf
不允许),请将两者更改==
为===
. 就目前而言:
fav = "4231";
plu.indexOf(fav) //-1
fav.isin(plu) //true