How to check if a string array contains one string in JavaScript?
This question already has an answer here:
There is an indexOf
method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.
You can use the indexOf
method and "extend" the Array class with the method contains
like this:
Array.prototype.contains = function(element){
return this.indexOf(element) > -1;
};
with the following results:
["A", "B", "C"].contains("A")
equals true
["A", "B", "C"].contains("D")
equals false
var stringArray = ["String1", "String2", "String3"];
return (stringArray.indexOf(searchStr) > -1)
链接地址: http://www.djcxy.com/p/13030.html
上一篇: 如何确定对象是否在数组中