pim*_*vdb 122 javascript
我正在检查一个变量,例如foo,与多个值的相等性.例如,
if( foo == 1 || foo == 3 || foo == 12 ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
关键是这个繁琐的任务代码相当多.我想出了以下内容:
if( foo in {1: 1, 3: 1, 12: 1} ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但这并不完全吸引我,因为我必须为对象中的项目提供冗余值.
有没有人知道对多个值进行相等检查的正确方法?
Gum*_*mbo 166
您可以使用数组并indexOf:
if ([1,3,12].indexOf(foo) > -1)
Run Code Online (Sandbox Code Playgroud)
Ali*_*ter 99
在ECMA2016中,您可以使用包含方法.这是我见过的最干净的方式.(所有主流浏览器均支持,IE除外(Polyfill在链接中)
if([1,3,12].includes(foo)) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
pim*_*vdb 17
使用提供的答案,我最终得到以下结果:
Object.prototype.in = function() {
for(var i=0; i<arguments.length; i++)
if(arguments[i] == this) return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
它可以被称为:
if(foo.in(1, 3, 12)) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
编辑:我最近遇到了这个'技巧',如果值是字符串并且不包含特殊字符,这很有用.对于特殊字符而言,由于转义而变得丑陋,并且由于这种情况也更容易出错.
/foo|bar|something/.test(str);
Run Code Online (Sandbox Code Playgroud)
更确切地说,这将检查确切的字符串,但对于简单的相等测试再次更复杂:
/^(foo|bar|something)$/.test(str);
Run Code Online (Sandbox Code Playgroud)
现在您可能有更好的解决方案来解决这种情况,但我更喜欢其他方式。
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
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢上面的解决方案,而不是 indexOf 检查,您还需要检查索引。
if ( arr.indexOf( foo ) !== -1 ) { }
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
这很容易扩展和可读:
switch (foo) {
case 1:
case 3:
case 12:
// ...
break
case 4:
case 5:
case 6:
// something else
break
}
Run Code Online (Sandbox Code Playgroud)
但不一定更容易:)
var a = [1,2,3];
if ( a.indexOf( 1 ) !== -1 ) { }
Run Code Online (Sandbox Code Playgroud)
请注意,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;
};
}
Run Code Online (Sandbox Code Playgroud)
另外,由于您要检查结果的值都是唯一的,因此您也可以使用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) );Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
109741 次 |
| 最近记录: |