确定字符串是否在 JavaScript 中的列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2430000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine if string is in list in JavaScript
提问by ErikE
In SQL we can see if a string is in a list like so:
在 SQL 中,我们可以查看字符串是否在列表中,如下所示:
Column IN ('a', 'b', 'c')
What's a good way to do this in JavaScript? It's so clunky to do this:
在 JavaScript 中这样做的好方法是什么?这样做很笨拙:
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:
或者可以使用 switch 功能:
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 7 as it's for a corporate intranet page. So ['a', 'b', 'c'].indexOf(str) !== -1won't work natively without some syntax sugar.
在这种情况下,我必须使用 Internet Explorer 7,因为它用于公司内部网页。所以['a', 'b', 'c'].indexOf(str) !== -1如果没有一些语法糖就不能在本地工作。
采纳答案by ErikE
EcmaScript 6
EcmaScript 6
If you're using ES6, you can construct an array of the items, and use includes:
如果您使用的是 ES6,您可以构造一个项目数组,并使用includes:
['a', 'b', 'c'].includes('b')
This has some inherent benefits over indexOfbecause it can properly test for the presence of NaNin the list, and can match missing array elements such as the middle one in [1, , 2]to undefined. includesalso works on JavaScript typed arrayssuch as Uint8Array.
这有一些固有的好处,indexOf因为它可以正确地测试NaN列表中的 存在,并且可以匹配缺失的数组元素,例如在[1, , 2]to 中的中间元素undefined。includes也适用于JavaScript 类型数组,例如Uint8Array.
If you're concerned about browser support (such as for IE or Edge), you can check Array.includesat CanIUse.Com, and if you want to target a browser or browser version that's missing includes, I recommend polyfill.iofor polyfilling.
如果您担心浏览器支持(例如 IE 或 Edge),您可以查看Array.includesCanIUse.Com,如果您想定位缺少的浏览器或浏览器版本includes,我推荐polyfill.io进行 polyfill。
Without An Array
没有数组
You could add a new isInListproperty to strings as follows:
您可以isInList向字符串添加新属性,如下所示:
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.
您可以对Number.prototype.
Array.indexOf
数组索引
If you are using a modern browser, indexOfalways works. However, for IE8 and earlier you'll need a polyfill.
如果您使用的是现代浏览器,则indexOf始终有效。但是,对于 IE8 及更早版本,您将需要一个 polyfill。
If indexOfreturns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN, and while it can match an explicit undefined, it can't match a missing element to undefinedas in the array [1, , 2].
如果indexOf返回 -1,则该项目不在列表中。但请注意,此方法将无法正确检查NaN,并且虽然它可以匹配显式undefined,但它无法将缺失元素匹配到undefined数组中[1, , 2]。
Polyfill for indexOfor includesin IE, or any other browser/version lacking support
填充工具用于indexOf或includes在IE或其他浏览器/版本缺乏支持
If you don't want to use a service like polyfill.ioas mentioned above, you can always include in your own source code standards-compliant custom polyfills. For example, Mozilla Developer Network has one for indexOf.
如果你不想使用像上面提到的polyfill.io这样的服务,你总是可以在你自己的源代码中包含符合标准的自定义 polyfill。例如,Mozilla Developer Network 有一个用于indexOf.
In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf()function that is not standards-compliant:
在我必须为 Internet Explorer 7 制定解决方案的这种情况下,我“推出了自己的”更简单的indexOf()不符合标准的功能版本:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(item) {
var i = this.length;
while (i--) {
if (this[i] === item) return i;
}
return -1;
}
}
However, I don't think modifying Array.prototypeis the best answer in the long term. Modifying Objectand Arrayprototypes 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 ... inwill return the new function name as one of the keys:
但是,我认为Array.prototype从长远来看,修改不是最好的答案。JavaScript 中的修改Object和Array原型可能会导致严重的错误。您需要决定这样做在您自己的环境中是否安全。主要注意的是,迭代一个数组(当 Array.prototype 添加了属性时)for ... in将返回新函数名称作为键之一:
Array.prototype.blah = function() { console.log('blah'); };
let arr = [1, 2, 3];
for (let x in arr) { console.log(x); }
// Result:
0
1
2
blah // Extra member iterated over!
Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break.
您的代码现在可能可以工作,但是如果将来有人添加了第三方 JavaScript 库或插件,而这些库或插件并没有积极防范继承的密钥,那么一切都可能会崩溃。
The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x))and only thenwork with that x.
避免这种破坏的旧方法是,在枚举期间,检查每个值以查看对象是否确实将其作为非继承属性使用if (arr.hasOwnProperty(x)),然后才使用它x。
The new ES6 way to avoid this extra-key problem is to use ofinstead of in, for (let x of arr). However, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to use includesas stated above.
新ES6的方式来避免这种额外关键的问题是使用of的,而不是in,for (let x of arr)。但是,除非您可以保证您的所有代码和第三方库都严格遵守此方法,否则就本问题而言,您可能只想使用includes上述方法。
回答by SLaks
You can call indexOf:
您可以致电indexOf:
if (['a', 'b', 'c'].indexOf(str) >= 0) {
//do something
}
回答by CMS
Most of the answers suggest the Array.prototype.indexOfmethod, the only problem is that it will not work on anyIE version before IE9.
大多数答案都提出了该Array.prototype.indexOf方法,唯一的问题是它不适用于IE9 之前的任何IE 版本。
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")) {
// ...
}
回答by harto
Arrays have an indexOfmethod which can be used to search for strings:
数组有一个indexOf方法可以用来搜索字符串:
js> a = ['foo', 'bar', 'baz']
foo,bar,baz
js> a.indexOf('bar')
1
js> a.indexOf('quux')
-1
回答by Esteban Küber
A trick I've used is
我用过的一个技巧是
>>> ("something" in {"a string":"", "somthing":"", "another string":""})
false
>>> ("something" in {"a string":"", "something":"", "another string":""})
true
You could do something like
你可以做类似的事情
>>> a = ["a string", "something", "another string"];
>>> b = {};
>>> for(var i=0; i<a.length;i++){b[a[i]]="";} /* Transform the array in a dict */
>>> ("something" in b)
true
回答by Brian McGinity
Here's mine:
这是我的:
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');
This one is faster if you're OK with passing an array:
如果你同意传递一个数组,这个会更快:
String.prototype.inList=function(list){
return (list.indexOf(this.toString()) != -1)
}
var x = 'abc';
if (x.inList(['aaa','bbb','abc']))
console.log('yes')
Here's the jsperf: http://jsperf.com/bmcgin-inlsit
这是 jsperf:http://jsperf.com/bmcgin-inlsit
回答by sospedra
RegExpis universal, but I understand that you're working with arrays. So, check out this approach. I use to use it, and it's very effective and blazing fast!
RegExp是通用的,但我知道您正在使用数组。所以,看看这个方法。我用过,效果非常好,速度超快!
var str = 'some string with a';
var list = ['a', 'b', 'c'];
var rx = new RegExp(list.join('|'));
rx.test(str);
You can also apply some modifications, i.e.:
您还可以应用一些修改,即:
One-liner
单线
new RegExp(list.join('|')).test(str);
Case insensitive
不区分大小写
var rx = new RegExp(list.join('|').concat('/i'));
And many others!
还有很多其他的!
回答by Tiago Medici
Using indexOf(it doesn't work with IE8).
使用 indexOf(它不适用于 IE8)。
if (['apple', 'cherry', 'orange', 'banana'].indexOf(value) >= 0) {
// found
}
To support IE8, you could implement Mozilla's indexOf.
要支持 IE8,您可以实现 Mozilla 的 indexOf。
if (!Array.prototype.indexOf) {
// indexOf polyfill code here
}
Regular Expressions via String.prototype.match (docs).
通过 String.prototype.match (docs) 的正则表达式。
if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
}
回答by pkaeding
In addition to indexOf(which other posters have suggested), using prototype's Enumerable.include()can make this more neat and concise:
除了indexOf(其他海报建议的)之外,使用原型的Enumerable.include()可以使其更加简洁明了:
var list = ['a', 'b', 'c'];
if (list.include(str)) {
// do stuff
}
回答by LG_PDX
Looks like you need to use in_array function.
看起来你需要使用 in_array 函数。
jQuery -> inArray
jQuery -> inArray
Prototype -> Array.indexOf
原型 -> Array.indexOf
Or, see these examples if you are not using jQuery or Prototype:
或者,如果您不使用 jQuery 或 Prototype,请查看这些示例:
- http://phpjs.org/functions/in_array:432
- http://www.bitrepository.com/equivalent-of-phps-in_array-function.html
- http://codingforums.com/showthread.php?t=63796
- http://phpjs.org/functions/in_array:432
- http://www.bitrepository.com/equivalent-of-phps-in_array-function.html
- http://codingforums.com/showthread.php?t=63796
Stylistic note:variables named thisthing thatthing, should be named to tell you something about what they contain (noun).
文体说明:命名为 thisthing thatthing 的变量,应该命名为告诉您它们包含的内容(名词)。

