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);
这篇关于根据值列表检查变量是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据值列表检查变量是否相等
基础教程推荐
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01