Determine if string is in list in JavaScript
In SQL we can see if a string is in a list like so:
Column IN ('a', 'b', 'c')
What's a good way to do this in JavaScript? It's so clunky to do this:
if (expression1 || expression2 || str === 'a' || str === 'b' || str === 'c') {
// do something
}
And I'm not sure about the performance or clarity of this:
if (expression1 || expression2 || {a:1, b:1, c:1}[str]) {
// do something
}
Or one could use the switch function:
var str = 'a',
flag = false;
switch (str) {
case 'a':
case 'b':
case 'c':
flag = true;
default:
}
if (expression1 || expression2 || flag) {
// do something
}
But that is a horrible mess. Any ideas?
In this case, I have to use Internet Explorer as it's for a corporate intranet page. So ['a', 'b', 'c'].indexOf(str) !== -1
won't work natively without some syntax sugar.
你可以调用indexOf
:
if (['a', 'b', 'c'].indexOf(str) >= 0) {
//do something
}
EcmaScript 6
If you're using ES6, you can construct an array of the items, and use includes
:
['a', 'b', 'c'].includes('b')
Without An Array
You could add a new isInList
property to strings as follows:
if (!String.prototype.isInList) {
String.prototype.isInList = function() {
let value = this.valueOf();
for (let i = 0, l = arguments.length; i < l; i += 1) {
if (arguments[i] === value) return true;
}
return false;
}
}
Then use it like so:
'fox'.isInList('weasel', 'fox', 'stoat') // true
'fox'.isInList('weasel', 'stoat') // false
You can do the same thing for Number.prototype
.
Polyfill for indexOf using IE8 and earlier
Short of ES6, you can do the same thing with indexOf
in most browsers (where IE8 and earlier is not part of "most").
In this situation, I eventually used the indexOf() function, and "rolled my own" for Internet Explorer 7.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(item) {
var i = this.length;
while (i--) {
if (this[i] === item) return i;
}
return -1;
}
}
However, long term I don't think modifying Array.prototype
is the best answer. Modifying Object
and Array
prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in
will return the new function name as one of the keys:
Array.prototype.blah = function() { console.log('blah'); };
for (var x in [1, 2, 3]) { console.log(x); }
// Result:
0
1
2
blah // Extra member iterated over
Most of the answers suggest the Array.prototype.indexOf
method, the only problem is that it will not work on any IE version before IE9.
As an alternative I leave you two more options that will work on all browsers:
if (/Foo|Bar|Baz/.test(str)) {
// ...
}
if (str.match("Foo|Bar|Baz")) {
// ...
}
链接地址: http://www.djcxy.com/p/25668.html
上一篇: 检查数组的任何元素是否满足条件