找出变量是否在数组中?

我有一个变量:

var code = "de"; 

我有一个数组:

 var countryList = ["de","fr","it","es"]; 

有人可以帮助我,因为我需要检查变量是否在countryList数组中 – 我的尝试在这里:

  if (code instanceof countryList) { alert('value is Array!'); } else { alert('Not an array'); } 

但是当它运行时我在console.log中收到以下错误:

TypeError:无效的’instanceof’操作数countryList

jQuery有一个实用程序函数来查找元素是否存在于数组中

 $.inArray(value, array) 

它返回array值的索引,如果array中不存在值,则返回-1 。 所以你的代码就像这样

 if( $.inArray(code, countryList) != -1){ alert('value is Array!'); } else { alert('Not an array'); } 

你需要使用Array.indexOf

 if (countryList.indexOf(code) >= 0) { // do stuff here } 

请注意,在IE8(以及可能的其他旧版浏览器)之前和之后都不支持它。 在这里了解更多相关信息。

您好像在寻找Array.indexOf函数。

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库,则可以使用适用于所有浏览器的inArray()函数。 它与indexOf()相同,如果找不到您要查找的元素,则返回-1。 所以你可以像这样使用它:

 if ( $.inArray( code, countryList ) === -1) { //the country code is not in the array ... } else { //the country code exists in the array ... } 

在jquery中你可以使用

jQuery.inArray() –搜索数组中的指定值并返回其索引(如果未找到,则返回-1)。

 if ($.inArray('de', countryList ) !== -1) { } 

对于javascript解决方案检查现有如何检查数组是否包含JavaScript中的对象?

 Array.prototype.contains = function(k) { for(p in this) if(this[p] === k) return true; return false; } for example: var list = ["one","two"]; list.contains("one") // returns true 

对于纯JavaScript解决方案,您只需遍历该数组即可。

 function contains( r, val ) { var i = 0, len = r.length; for(; i < len; i++ ) { if( r[i] === val ) { return i; } } return -1; } 

使用jQuery

你可以使用$ .inArray()

 $.inArray(value, array) 

返回项的索引,如果未找到,则返回-1