在SQL中,我们可以看到一个字符串是否像这样在一个列表中:
Column IN ('a', 'b', 'c')
JavaScript中有什么好方法呢?这样做太笨拙了:
if (expression1 || expression2 || str === 'a' || str === 'b' || str === 'c') {
// do something
}
我不确定它的表现和清晰度:
if (expression1 || expression2 || {a:1, b:1, c:1}[str]) {
// do something
}
或者可以使用switch函数:
var str = 'a',
flag = false;
switch (str) {
case 'a':
case 'b':
case 'c':
flag = true;
default:
}
if (expression1 || expression2 || flag) {
// do something
}
但这是一个可怕的混乱。什么好主意吗?
在这种情况下,我必须使用Internet Explorer 7,因为它是用于公司内部网页面的。所以['a', 'b', 'c']. indexof (str) !== -1如果没有一些语法糖就不能正常工作。
使用indexOf(它不支持IE8)。
if (['apple', 'cherry', 'orange', 'banana'].indexOf(value) >= 0) {
// found
}
为了支持IE8,你可以实现Mozilla的indexOf。
if (!Array.prototype.indexOf) {
// indexOf polyfill code here
}
通过String.prototype.match (docs)实现正则表达式。
if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
}
我的解决方案的结果是这样的语法:
// Checking to see if var 'column' is in array ['a', 'b', 'c']
if (column.isAmong(['a', 'b', 'c']) {
// Do something
}
我通过扩展基本的Object原型来实现这一点,像这样:
Object.prototype.isAmong = function (MyArray){
for (var a=0; a<MyArray.length; a++) {
if (this === MyArray[a]) {
return true;
}
}
return false;
}
我们也可以将该方法命名为isInArray(但可能不是inArray)或简单地命名为isIn。
优点:简单、直接、自文档化。
这是我的:
String.prototype.inList=function(list){
return (Array.apply(null, arguments).indexOf(this.toString()) != -1)
}
var x = 'abc';
if (x.inList('aaa','bbb','abc'))
console.log('yes');
else
console.log('no');
如果你可以传递一个数组,这个会更快:
String.prototype.inList=function(list){
return (list.indexOf(this.toString()) != -1)
}
var x = 'abc';
if (x.inList(['aaa','bbb','abc']))
console.log('yes')
下面是jsperf: http://jsperf.com/bmcgin-inlsit