在Javascript中减少IF语句中的多个OR

Mis*_*hko 6 javascript

有没有更简单的方法来重写JavaScript中的以下条件?

if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}
Run Code Online (Sandbox Code Playgroud)

Gum*_*mbo 17

您可以使用有效值数组并使用indexOf以下方法对其进行测试:

if ([1, 3, 4, 17, 80].indexOf(x) != -1)
Run Code Online (Sandbox Code Playgroud)

编辑     注释indexOf刚刚添加到ECMAScript 5中,因此未在每个浏览器中实现.但如果缺少,您可以使用以下代码添加它:

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;
  };
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您已经在使用JavaScript框架,那么您也可以使用该方法的实现.


小智 7

switch (x) {
    case 1:
    case 3:
    case 4:
    case 17:
    case 80:
        //code
        break;
    default:
        //code
}
Run Code Online (Sandbox Code Playgroud)

  • 不是很简单,但是一个不错的选择,并且很好地利用了不使用中断,你忘了把它放在`case 80中的代码之后:` (3认同)