JavaScript:检查变量是否等于两个或多个值的简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12116326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Simple way to check if variable is equal to two or more values?
提问by Adam Templeton
Is there an easier way to determine if a variable is equal to a range of values, such as:
是否有更简单的方法来确定变量是否等于某个范围的值,例如:
if x === 5 || 6
rather than something obtuse like:
而不是像这样的钝器:
if x === 5 || x === 6
?
?
回答by Yoshi
You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:
您可以将值存储在数组中,并使用以下命令检查数组中是否存在变量[].indexOf:
if([5, 6].indexOf(x) > -1) {
// ...
}
If -1is returned then the variable doesn't exist in the array.
如果-1返回,则该变量不存在于数组中。
回答by zzzzBov
Depends on what sort of test you're performing. If you've got static strings, this is very easy to check via regular expressions:
取决于您正在执行的测试类型。如果你有静态字符串,这很容易通过正则表达式检查:
if (/^[56ab]$/.test(item)) {
//-or-
if (/^(foo|bar|baz|fizz|buzz)$/.test(item)) {
doStuff();
} else {
doOtherStuff();
}
If you've got a small set of values (string or number), you can use a switch:
如果您有一小组值(字符串或数字),则可以使用switch:
switch (item) {
case 1:
case 2:
case 3:
doStuff();
break;
default:
doOtherStuff();
break;
}
If you've got a long list of values, you should probably use an array with ~arr.indexOf(item), or arr.contains(item):
如果您有很长的值列表,您可能应该使用带有~arr.indexOf(item), 或的数组arr.contains(item):
vals = [1,3,18,3902,...];
if (~vals.indexOf(item)) {
doStuff();
} else {
doOtherStuff();
}
Unfortunately Array.prototype.indexOfisn't supported in some browsers. Fortunately a polyfill is available. If you're going through the trouble of polyfilling Array.prototype.indexOf, you might as well add Array.prototype.contains.
不幸的Array.prototype.indexOf是,某些浏览器不支持。幸运的是,有一个 polyfill 可用。如果您正在经历 polyfilling 的麻烦Array.prototype.indexOf,您不妨添加Array.prototype.contains.
Depending on how you're associating data, you could store a dynamic list of strings within an object as a map to other relevant information:
根据您关联数据的方式,您可以在对象中存储动态字符串列表,作为其他相关信息的映射:
var map = {
foo: bar,
fizz: buzz
}
if (item in map) {
//-or-
if (map.hasOwnProperty(item)) {
doStuff(map[item]);
} else {
doOtherStuff();
}
inwill check the entire prototype chain while Object.prototype.hasOwnPropertywill only check the object, so be aware that they are different.
in将检查整个原型链而Object.prototype.hasOwnProperty只会检查对象,因此请注意它们是不同的。
回答by Jo?o Silva
It's perfectly fine. If you have a longer list of values, perhaps you can use the following instead:
完全没问题。如果您有更长的值列表,也许您可以使用以下内容:
if ([5,6,7,8].indexOf(x) > -1) {
}
回答by 0x499602D2
回答by Greg Perham
This is what I've decided to use:
这是我决定使用的:
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;
}
You would use it like this:
你会像这样使用它:
var fav = 'pear',
fruit = ['apple', 'banana', 'orange', 'pear'],
plu = [4152, 4231, 3030, 4409];
if (fav.isin(fruit, plu, 'eggs', 'cheese')) {
//do something cool
}
The advantages are:
优点是:
- it works in IE < 9;
- it reads naturally from left to right;
- you can feed it arrays or separate values.
- 它适用于 IE < 9;
- 它从左到右自然地阅读;
- 您可以为它提供数组或单独的值。
If you don't want to allow type coercion (indexOfdoes not), change the two ==to ===. As it stands:
如果您不想允许类型强制(indexOf不允许),请将两者更改==为===. 就目前而言:
fav = "4231";
plu.indexOf(fav) //-1
fav.isin(plu) //true
回答by ckozl
no, there might be a few tricks that are case specific but in general i write code like this:
不,可能有一些特定于案例的技巧,但总的来说,我编写的代码如下:
if (someVariable === 1 ||
someVariable === 2 ||
someVariable === 7 ||
someVariable === 12 ||
someVariable === 14 ||
someVariable === 19) {
doStuff();
moreStuff();
} else {
differentStuff();
}
回答by monitorjbl
The simple answer is no. You can use a switch statement, which is easier to read if you are comparing a lot of string values, but using it for two values wouldn't look any better.
简单回答是不。您可以使用 switch 语句,如果您要比较大量字符串值,它会更容易阅读,但将它用于两个值看起来不会更好。
回答by Jeremy Thille
[Edit] this seems to work, but as Dan pointed out, it is actually a false positive. Do not use this method. I leave it here for educational purposes.
[编辑] 这似乎有效,但正如丹指出的那样,它实际上是一个误报。不要使用这种方法。我把它留在这里是为了教育目的。
Easiest way I know :
我知道的最简单的方法:
a = [1,2,3,4,5];
if(3 in a) alert("true"); // will alert true
Tested in Chrome console. Not sure if it works in other browsers.
在 Chrome 控制台中测试。不确定它是否适用于其他浏览器。

