ngp*_*und 19 javascript arrays
我有一个变量:
var code = "de";
Run Code Online (Sandbox Code Playgroud)
我有一个数组:
var countryList = ["de","fr","it","es"];
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我,因为我需要检查变量是否在countryList数组中 - 我的尝试在这里:
if (code instanceof countryList) {
alert('value is Array!');
}
else {
alert('Not an array');
}
Run Code Online (Sandbox Code Playgroud)
但是当它运行时我在console.log中收到以下错误:
TypeError:无效的'instanceof'操作数countryList
dsg*_*fin 29
你需要使用Array.indexOf:
if (countryList.indexOf(code) >= 0) {
// do stuff here
}
Run Code Online (Sandbox Code Playgroud)
请注意,在IE8(以及可能的其他传统浏览器)之前和之后都不支持它.在这里了解更多相关信息.
Suk*_*nda 21
jQuery有一个实用程序函数来查找元素是否存在于数组中
$.inArray(value, array)
Run Code Online (Sandbox Code Playgroud)
它返回值的索引array以及-1数组中是否存在值.所以你的代码可以是这样的
if( $.inArray(code, countryList) != -1){
alert('value is Array!');
} else {
alert('Not an array');
}
Run Code Online (Sandbox Code Playgroud)
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
...
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用更简单的使用函数的方法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
...
}
Run Code Online (Sandbox Code Playgroud)
我会使用第二种算法,因为它更简单。但第一个算法也很好,因为它更具可读性。两者收入相同,但第二个性能更好,时间更短。但是,较旧的浏览器(IE<9)不支持它。
如果您使用 JQuery 库,则可以使用inArray()适用于所有浏览器的功能。indexOf()如果没有找到您要查找的元素,它与返回 -1 相同。所以你可以这样使用它:
if ( $.inArray( code, countryList ) === -1) {
//the country code is not in the array
...
} else {
//the country code exists in the array
...
}
Run Code Online (Sandbox Code Playgroud)