假设我有这个:

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

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


一些浏览器支持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;
  };
}

源。


试试这个:

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

if(array.indexOf("67") != -1) // is in array

根据可用的JavaScript版本,你可以使用indexOf:

返回数组中给定元素所在的第一个索引,如果不存在则返回-1。

或者一些:

测试数组中的某些元素是否通过了所提供函数实现的测试。

但是,如果你做了这种存在性检查,你会更好地使用一个对象来存储你的字符串(或者一个对象以及数组,这取决于你对你的数据做什么)。


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
}

使用Underscore.js

它跨浏览器兼容,并可以执行二进制搜索,如果您的数据已排序。

_ indexOf。

_。indexOf(array, value, [isSorted])返回可以在数组中找到value的索引,如果value在数组中不存在,则返回-1。 除非缺少indexOf函数,否则使用本机indexOf函数。如果你 处理一个大数组,你知道数组已经 为isSorted传递true以使用更快的二分搜索。

例子

//Tell underscore your data is sorted (Binary Search)
if(_.indexOf(['2','3','4','5','6'], '4', true) != -1){
    alert('true');
}else{
    alert('false');   
}

//Unsorted data works to!
if(_.indexOf([2,3,6,9,5], 9) != -1){
    alert('true');
}else{
    alert('false');   
}

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

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

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


如前所述,如果您的浏览器支持indexOf(),那就太好了! 如果不是的话,你需要对它进行polyfil,或者依赖于像lodash/underscore这样的多功能带。

只是想添加这个更新的ES2016新增内容(以保持这个问题的更新):

Array.prototype.includes ()

if (blockedTile.includes("118")) {
    // found element
}

在数组的例子中,它在php (in_array)中是一样的

 var ur_fit = ["slim_fit", "tailored", "comfort"];
 var ur_length = ["length_short", "length_regular", "length_high"];
    if(ur_fit.indexOf(data_this)!=-1){
        alert("Value is avail in ur_fit array");
    }
    else if(ur_length.indexOf(data_this)!=-1){      
         alert("value is avail in ur_legth array"); 

    }

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

您可以尝试下面的代码。检查http://api.jquery.com/jquery.grep/

var blockedTile = new Array("118", "67", "190", "43", "135", "520");
var searchNumber = "11878";
arr = jQuery.grep(blockedTile, function( i ) {
  return i === searchNumber;
});
if(arr.length){ console.log('Present'); }else{ console.log('Not Present'); }

检查加勒比海盗。长度大于0表示字符串存在,否则不存在。


我认为最简单的方法是:

(118 in blockedTile); //is true 

Assuming that you're only using the array for lookup, you can use a Set (introduced in ES6), which allows you to find an element in O(1), meaning that lookup is sublinear. With the traditional methods of .includes() and .indexOf(), you still may need to look at all 500 (ie: N) elements in your array if the item specified doesn't exist in the array (or is the last item). This can be inefficient, however, with the help of a Set, you don't need to look at all elements, and instead, instantly check if the element is within your set:

const blockedTile = new集((“118”、“67”、“190”、“43”、“135”、“520”)); 如果(blockedTile.has (" 118 ")) { // 118在你的Set中 console.log(“发现118”); }

如果出于某种原因需要将集合转换回数组,可以通过使用array .from()或扩展语法(…)来实现,但是,这将遍历整个集合的内容(将是O(N))。集合也不会保留重复项,这意味着数组不会包含重复项。


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

    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");
    }