假设我有这个:

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

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


当前回答

为什么不用array。filter呢?

var array = ['x','y','z'];
array.filter(function(item,index,array){return(item==YOURVAL)}).

只需将其复制到代码中,就可以了:

Array.prototype.inArray = function (searchedVal) {
return this.filter(function(item,index,array){return(item==searchedVal)}).length==true
}

其他回答

一些浏览器支持Array.indexOf()。

如果不是,你可以通过它的原型来扩充Array对象,就像这样…

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n) // shortcut for verifying if it's NaN
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

源。

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

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

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字符串,您可以在旧浏览器中测试字符串。

试试这个:

if(blockedTile.indexOf("118") != -1)
{  
   // element found
}

我这边的一小段代码(数组的自定义函数):

    Array.prototype.in_array = function (array) {
        var $i = 0;
        var type = typeof array;
        while (this[$i]) {
            if ((type == ('number') || type == ('string'))  && array == this[$i]) {
                return true;
            } else if (type == 'object' && array instanceof Array && array.in_array(this[$i])) {
                return true
            }
            $i++;
        }
        return false;
    };


    var array = [1, 2, 3, "a", "b", "c"];

    //if string in array
    if (array.in_array('b')) {
        console.log("in array");
    }

    //if number in array
    if (array.in_array(3)) {
        console.log("in array");
    }

    // if one from array in array
    if (array.in_array([1, 'b'])) {
        console.log("in array");
    }