Reduce multiple ORs in IF statement in JavaScript

前端 未结 8 560
借酒劲吻你
借酒劲吻你 2020-12-07 02:17

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

if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}
8条回答
  •  庸人自扰
    2020-12-07 02:52

    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.

提交回复
热议问题