[英]Reduce multiple ORs in IF statement in JavaScript
有没有更简单的方法来重写 JavaScript 中的以下条件?
if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}
You could use an array of valid values and test it with indexOf
:您可以使用一组有效值并使用indexOf
对其进行测试:
if ([1, 3, 4, 17, 80].indexOf(x) != -1)
Edit Note that indexOf
was just added in ECMAScript 5 and thus is not implemented in every browser.编辑请注意, indexOf
刚刚添加到 ECMAScript 5 中,因此并未在每个浏览器中实现。 But you can use the following code to add it if missing:但是如果缺少,您可以使用以下代码添加它:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
Or, if you're already using a JavaScript framework, you can also use its implementation of that method.或者,如果您已经在使用 JavaScript 框架,您也可以使用该方法的实现。
switch (x) {
case 1:
case 3:
case 4:
case 17:
case 80:
//code
break;
default:
//code
}
This is a little function I found somewhere on the web:这是我在网上找到的一个小功能:
function oc(a) {
var o = {};
for (var i = 0; i < a.length; i++) {
o[a[i]] = '';
}
return o;
}
Used like this:像这样使用:
if (x in oc(1, 3, 4, 17, 80)) {...}
I'm using it for strings myself;我自己将它用于字符串; haven't tried with numbers, but I guess it would work.没有尝试过数字,但我想它会起作用。
正则表达式测试使用 x 的字符串值:
if(/^[134]|17|80$/.test(x)){/*...*/}
你可以优化你自己的例子,去掉一些字符,让它看起来更容易..:
if (x == 1 || x == 3 || x == 4 || x == 17 || x == 80) { ... }
many options很多选择
if ([0, 1, 3, 4, 17, 80].indexOf(x) > 0)
if(/^(1|3|4|17|80)$/.test(x))
if($.inArray(x, [1, 3, 4, 17, 80])
another one, based on Ed's answer另一个,基于Ed 的回答
function list() {
for (var i = 0, o = {}; i < arguments.length; i++)
o[arguments[i]] = '';
return o;
}
if(x in list(1, 3, 4, 17, 80))...
You can also use the Array.includes the simplest way...您还可以使用Array.includes最简单的方法...
if([1,3,4,17,80].includes(x)){
console.log(true);
// rest of the code
}
Inspired by @Santosh I created a simplified version:受@Santosh 的启发,我创建了一个简化版本:
const input = x => [1, 3, 4, 17, 80].includes(x); console.log(input(10)); console.log(input(1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.