Javascript 根据值列表检查变量相等性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4728144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:48:19  来源:igfitidea点击:

Check variable equality against a list of values

javascript

提问by pimvdb

I'm checking a variable, say foo, for equality to a number of values. For example,

我正在检查一个变量,例如foo,是否与多个值相等。例如,

if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}

The point is that it is rather much code for such a trivial task. I came up with the following:

关键是对于这样一个微不足道的任务,它是相当多的代码。我想出了以下内容:

if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

但这并不完全吸引我,因为我必须为对象中的项目赋予冗余值。

Does anyone know a decent way of doing an equality check against multiple values?

有没有人知道对多个值进行平等检查的体面方法?

采纳答案by pimvdb

Using the answers provided, I ended up with the following:

使用提供的答案,我最终得到以下结果:

Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}

It can be called like:

它可以被称为:

if(foo.in(1, 3, 12)) {
    // ...
}


Edit:I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

编辑:我最近遇到了这个“技巧”,如果值是字符串并且不包含特殊字符,它会很有用。对于特殊字符,由于转义而变得丑陋,并且因此更容易出错。

/foo|bar|something/.test(str);

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

更准确地说,这将检查确切的字符串,但对于简单的相等性测试,这又变得更加复杂:

/^(foo|bar|something)$/.test(str);

回答by Gumbo

You could use an array and indexOf:

您可以使用数组和indexOf

if ([1,3,12].indexOf(foo) > -1)

回答by Alister

In ECMA2016 you can use the includesmethod. It's the cleanest way I've seen. (Supported by all major browsers, except IE (Polyfill is in the link)

在 ECMA2016 中,您可以使用includes方法。这是我见过的最干净的方式。(除 IE 外,所有主流浏览器都支持(Polyfill 在链接中)

if([1,3,12].includes(foo)) {
    // ...
}

回答by Elian Ebbing

You can write if(foo in L(10,20,30))if you define Lto be

if(foo in L(10,20,30))如果你定义L为,你可以写

var L = function()
{
    var obj = {};
    for(var i=0; i<arguments.length; i++)
        obj[arguments[i]] = null;

    return obj;
};

回答by orlp

This is easily extendable and readable:

这很容易扩展和可读:

switch (foo) {
    case 1:
    case 3:
    case 12:
        // ...
        break

    case 4:
    case 5:
    case 6:
        // something else
        break
}

But not necessarily easier :)

但不一定更容易:)

回答by meder omuraliev

var a = [1,2,3];

if ( a.indexOf( 1 ) !== -1 ) { }

Note that indexOf is not in the core ECMAScript. You'll need to have a snippet for IE and possibly other browsers that dont support Array.prototype.indexOf.

请注意 indexOf 不在核心 ECMAScript 中。您需要有一个用于 IE 和可能不支持 Array.prototype.indexOf 的其他浏览器的代码段。

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

回答by Ivan Sivak

Also, since the values against which you're checking the result are all unique you can use the Set.prototype.has()as well.

此外,由于您检查结果所依据的值都是唯一的,您也可以使用Set.prototype.has()

var valid = [1, 3, 12];
var goodFoo = 3;
var badFoo = 55;

// Test
console.log( new Set(valid).has(goodFoo) );
console.log( new Set(valid).has(badFoo) );

回答by Javed Shaikh

Now you may have a better solution to resolve this scenario, but other way which i preferred.

现在您可能有更好的解决方案来解决这种情况,但我更喜欢其他方式。

const arr = [1,3,12]
if( arr.includes(foo)) { // it will return true if you `foo` is one of array values else false
  // code here    
}

I preferred above solution over the indexOf check where you need to check index as well.

我更喜欢上面的解决方案,而不是 indexOf 检查,您还需要检查索引。

includes docs

包括文档

if ( arr.indexOf( foo ) !== -1 ) { }

回答by Victor

This is a little helper arror function:

这是一个小助手 arror 函数:

const letters = ['A', 'B', 'C', 'D'];

function checkInList(arr, val) {
  return arr.some(arrVal => val === arrVal);
}

checkInList(letters, 'E');   // false
checkInList(letters, 'A');   // true

More info here...

更多信息在这里...

回答by Greg Perham

I liked the accepted answer, but thought it would be neat to enable it to take arrays as well, so I expanded it to this:

我喜欢接受的答案,但认为让它也能接受数组会很好,所以我将其扩展为:

Object.prototype.isin = function() {
    for(var i = arguments.length; i--;) {
        var a = arguments[i];
        if(a.constructor === Array) {
            for(var j = a.length; j--;)
                if(a[j] == this) return true;
        }
        else if(a == this) return true;
    }
    return false;
}

var lucky = 7,
    more = [7, 11, 42];
lucky.isin(2, 3, 5, 8, more) //true

You can remove type coercion by changing ==to ===.

您可以通过更改==为来移除类型强制===