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);
这篇关于根据值列表检查变量是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据值列表检查变量是否相等
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01