假设我有这个:

var blockedTile = new Array("118", "67", "190", "43", "135", "520");

还有更多的数组元素,但出于可读性考虑,这些元素很少。无论如何,我可以做一个“for”循环,但每次你点击地图时,它会做500个循环……有没有其他方法来查看某个字符串是否在数组中?


当前回答

我认为最简单的方法是:

(118 in blockedTile); //is true 

其他回答

var myArray = [2,5,6,7,9,6];
myArray.includes(2) // is true
myArray.includes(14) // is false

我认为最简单的方法是:

(118 in blockedTile); //is true 

我会使用不同的数据结构,因为数组似乎不是最好的解决方案。

使用对象作为哈希表,而不是数组,如下所示:

(也发布在jsbin中)

var arr = ["x", "y", "z"];
var map = {};
for (var k=0; k < arr.length; ++k) {
  map[arr[k]] = true;
}

function is_in_map(key) {
  try {
    return map[key] === true;
  } catch (e) {
    return false;
  }
}


function print_check(key) {
  console.log(key + " exists? - " + (is_in_map(key) ? "yes" : "no"));
}

print_check("x");
print_check("a");

控制台输出:

x exists? - yes
a exists? - no

这是一个简单的解决方案。如果你更喜欢面向对象的方法,那么在谷歌中搜索“js hashtable”。

恕我直言,最兼容旧浏览器

Array.prototype.inArray = function(needle){ 返回Array(this).join(",").indexOf(needle) >-1; } var foods =["奶酪","洋葱","泡菜","火腿"]; test = foods.inArray("Lemon"); console.log(“Lemon is”+ (test ?"": "not ") + "in the list.");

通过将Array副本转换为CSV字符串,您可以在旧浏览器中测试字符串。

function in_array(needle, haystack){
    var found = 0;
    for (var i=0, len=haystack.length;i<len;i++) {
        if (haystack[i] == needle) return i;
            found++;
    }
    return -1;
}
if(in_array("118",array)!= -1){
//is in array
}