简体   繁体   English

检查数组是否包含给定元素

[英]Checking if array contains given element

I have an array of numbers and dynamically adding new numbers to that array in for loop. 我有一个数字数组,并在for循环中向该数组动态添加新数字。 But I need to avoid adding values that already exist in array. 但是我需要避免添加数组中已经存在的值。 Is there a JS native way to check the presence of some value in array without doing 2nd nested loop. 是否有一种JS本机方法可以检查数组中是否存在某些值,而无需执行第二个嵌套循环。 I don't want to use nested loop because the size of array may vary up to 10000 我不想使用嵌套循环,因为数组的大小最多可能变化10000

You can use JavaScript's native Array.prototype.indexOf , supported in most browsers: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf 您可以使用大多数浏览器支持的JavaScript本机Array.prototype.indexOfhttps : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

 var a = [1, 2, 3];
 console.log(a.indexOf(4));   // -1

indexOf is faster than a for-loop but the algorithmic complexity is still O(n^2) . indexOf比for循环快,但是算法复杂度仍为O(n^2) If the size of the array gets much larger, consider a different data structure such as a hash table. 如果数组的大小变得更大,请考虑使用其他数据结构,例如哈希表。

Just use includes . 只需使用includes

var array1 = [1, 2, 3];
console.log(array1.includes(2)); // true

You can easily avoid a for loop by using a while loop. 您可以使用while循环轻松避免for循环。 [Pause for laughter...] But seriously, even the built-in Array.indexOf() method (supported by most browsers) probably uses a loop internally. [暂停笑声...]但是,严重的是,即使内置的Array.indexOf()方法(大多数浏览器都支持)也可能在内部使用循环。

You could use a plain object instead, and add each number to the object as a property, then afterwards take the values from the object and put them in an actual array (or just use them in the object if that is convenient). 您可以改用普通对象,然后将每个数字作为属性添加到对象中,然后从对象中获取值并将它们放入实际数组中(如果方便,也可以在对象中使用它们)。 Then you only have to loop through the "up to 10000" numbers once at the end: 然后,您只需要在最后一次循环遍历“最多10000”个数字:

var numbersObj = {},
    numbersArray = [];

// your existing for statement here
for (var i=0; i<something; i++) {
   var currentNumber = somethingElse(); // whatever your existing code is to
                                    // determine the number to add goes here

   // put the number in the object (as a key)
   numersObj[currentNumber] = true;
}

// copy numbers out of object into array
for (var k in numbersObj)
   if (numbersObj.hasOwnProperty(k))
      numbersArray.push(k);

After which numbersArray contains unique numbers only. 之后, numbersArray仅包含唯一数字。 The if test with .hasOwnProperty() is "optional" depending on your point of view. .hasOwnProperty()的if测试是“可选的”,具体取决于您的观点。

Within the first loop you could check if numbersObj already holds the currentNumber : 在第一个循环中,您可以检查numbersObj已经拥有currentNumber

if (!numbersObj[currentNumber])
   numbersObj[currentNumber] = true;

Or just (over)write it every time like I did in the first code block. 或者只是像我在第一个代码块中那样每次都(重写)编写它。

try this, 尝试这个,

function eleContainsInArray(arr,element){
    if(arr != null && arr.length >0){
        for(var i=0;i<arr.length;i++){
            if(arr[i] == element)
                return true;
        }
    }
    return false;
 } 

There is Array.indexOf which is supported from some browser, you can use this snippets of code to support all browser 有些浏览器支持Array.indexOf ,您可以使用此代码段来支持所有浏览器

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM