instanceof
是用於檢查對象是否是特定類型(這是一個完全不同的主題)的。所以,而不是你寫的代碼,你應該在數組中查找。您可以檢查這樣的每一個元素:
var found = false;
for(var i = 0; i < countryList.length; i++) {
if (countryList[i] === code) {
found = true;
break;
}
}
if (found) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}
或者你可以使用使用indexOf()
功能的簡單的方法。每個數組都有一個indexOf()
函數,它循環一個元素並返回數組中的索引。如果找不到該元素,則返回-1。所以,你檢查輸出的indexOf()
,看它是否已經找到任何您的字符串匹配的數組中:
if (countryList.indexOf(code) === -1) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}
我會使用第二算法,因爲它更簡單。但是第一個算法也很好,因爲它更具可讀性。兩者都有相同的收入,但第二個有更好的表現,並且更短。但是,舊版瀏覽器不支持它(IE < 9)。
如果您使用的是JQuery庫,則可以使用可在所有瀏覽器中工作的函數。它與indexOf()
相同,如果找不到要查找的元素,則回退-1。所以你可以這樣使用它:
if ($.inArray(code, countryList) === -1) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}
-1標籤問題如果在接受答案之前給出的相同答案未被接受... –