在Javascript中减少IF语句中的多个OR [英] Reduce multiple ORs in IF statement in Javascript

查看:167
本文介绍了在Javascript中减少IF语句中的多个OR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


推荐答案

您可以使用有效值数组并使用 indexOf

You could use an array of valid values and test it with indexOf:

if ([1, 3, 4, 17, 80].indexOf(x) != -1)






编辑请注意 indexOf 刚刚在ECMAScript 5中添加,因此并未在每个浏览器中实现。但您可以使用以下代码添加它缺失:


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;
  };
}

或者,如果你已经在使用JavaScript框架,你也可以使用它的实现方法。

Or, if you’re already using a JavaScript framework, you can also use its implementation of that method.

这篇关于在Javascript中减少IF语句中的多个OR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆