我有一個字符串數組和一個字符串。我想測試這個字符串對數組值,並應用條件的結果 - 如果數組包含字符串做「A」,否則做「B」。如何檢查一個字符串數組是否包含JavaScript中的一個字符串?
我該怎麼做?
我有一個字符串數組和一個字符串。我想測試這個字符串對數組值,並應用條件的結果 - 如果數組包含字符串做「A」,否則做「B」。如何檢查一個字符串數組是否包含JavaScript中的一個字符串?
我該怎麼做?
有一個indexOf
方法,所有陣列具有(除了Internet Explorer 8和下文),這將返回一個元素的索引陣列中,或-1,如果它不是在陣列中:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
如果您需要支持舊的IE瀏覽器,則可以使用the MDN article中的代碼來填充此方法。
這會爲你做它:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle)
return true;
}
return false;
}
我發現它在堆棧溢出問題JavaScript equivalent of PHP's in_array()。
而且您重新創建了現代瀏覽器支持的indexOf。 – epascarello
......在IE9之前IE不支持 - 包括我自己在內的很多人都必須爲IE8開發(大多數情況下也很遺憾IE7)。無可否認,創建indexOf函數的原型方法是我發佈 – ollie
var stringArray = ["String1", "String2", "String3"];
return (stringArray.indexOf(searchStr) > -1)
可以使用indexOf
方法和 「擴展」 Array類與方法contains
這樣的:
Array.prototype.contains = function(element){
return this.indexOf(element) > -1;
};
結果如下:
["A", "B", "C"].contains("A")
等於true
["A", "B", "C"].contains("D")
等於false
好的解決方案的好辦法,但在使用indexOf時,值得一提的是舊IE版本的兼容性問題。 –
沒人關心即使微軟:D – andygoestohollywood
@andygoestohollywood可悲的是一些公司仍然使用IE瀏覽器。僅僅因爲一些公司進入石器時代並不意味着你應該拋售9%的市場。 –
創建此函數原型:
Array.prototype.contains = function (needle) {
for (i in this) {
if (this[i] == needle) return true;
}
return false;
}
,然後你可以用下面的代碼在數組中搜索X
if (x.contains('searchedString')) {
// do a
}
else
{
// do b
}
閱讀[爲什麼使用「for ... in」與數組迭代這樣一個壞主意?](https://stackoverflow.com/questions/500504/why-is-using-換在-與陣列迭代-這樣-A-壞主意) – Bergi
檢查出來:http://stackoverflow.com/questions/237104/array -containsobj-in-javascript –
indexOf [MDN文檔](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf) – epascarello
遍歷數組並逐個比較! – SachinGutte