根据值列表检查变量相等性 [英] Check variable equality against a list of values

查看:115
本文介绍了根据值列表检查变量相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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?

推荐答案

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

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

可以这样调用:

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






编辑:我最近遇到了这个诡计如果值是字符串并且不包含特殊字符,则非常有用。对于特殊字符而言,由于转义而变得丑陋,并且由于这种情况也更容易出错。


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

这篇关于根据值列表检查变量相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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