Reduce multiple ORs in IF statement in Javascript

2020-02-01 19:31发布

Is there a simpler way to rewrite the following condition in JavaScript?

if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}

标签: javascript
7条回答
看我几分像从前
2楼-- · 2020-02-01 19:54

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

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))...
查看更多
SAY GOODBYE
3楼-- · 2020-02-01 19:59

You could use an array of valid values and test it with 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. 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.

查看更多
倾城 Initia
4楼-- · 2020-02-01 19:59

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.

查看更多
5楼-- · 2020-02-01 20:01
switch (x) {
    case 1:
    case 3:
    case 4:
    case 17:
    case 80:
        //code
        break;
    default:
        //code
}
查看更多
▲ chillily
6楼-- · 2020-02-01 20:01

a regular expression test uses the string value of x:

if(/^[134]|17|80$/.test(x)){/*...*/}
查看更多
孤傲高冷的网名
7楼-- · 2020-02-01 20:13

You can also use the Array.includes the simplest way...

    if([1,3,4,17,80].includes(x)){
        console.log(true); 
        // rest of the code
    }
查看更多
登录 后发表回答