Javascript 如何检查列表是否包含javascript中的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36782940/
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
How to check if a list contains a string in javascript?
提问by Gallaxhar
How can I test if the string "Orange" without quotes, exists in a list such as the one below, using javascript?
如何使用javascript测试不带引号的字符串“Orange”是否存在于如下列表中?
var suggestionList = ["Apple", "Orange", "Kiwi"];
回答by ippi
indexOf()is the default to use in such cases.
indexOf()是在这种情况下使用的默认值。
if( suggestionList.indexOf("Orange") > -1 ) {
console.log("success");
}
.indexOf() returns the position in the array (or string) of the found element. When no elements are found it returns -1
.
.indexOf() 返回找到的元素在数组(或字符串)中的位置。当没有找到元素时,它返回-1
。
Things to consider:
需要考虑的事项:
- It willreturn 0 if the first object matches, so you cannotjust cast to boolean.
- Since es2016 you can use
suggestionList.includes('Kiwi');
which will return a boolean directly. (Does not work in internet explorer, but works in IEdge) - includes polyfill for older browsers: https://babeljs.io/docs/usage/polyfill/
- 它会如果第一个对象匹配,这样你就返回0不能只投为布尔值。
- 从 es2016 开始,您可以使用
suggestionList.includes('Kiwi');
which 将直接返回一个布尔值。(在 Internet Explorer 中不起作用,但在 IEdge 中有效) - 包括旧浏览器的 polyfill:https: //babeljs.io/docs/usage/polyfill/