根据值列表检查变量是否相等

Check variable equality against a list of values(根据值列表检查变量是否相等)

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

问题描述

我正在检查一个变量,比如 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);

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

本文标题为:根据值列表检查变量是否相等

基础教程推荐