Javascript 检查元素是否存在于数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7378228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:02:31  来源:igfitidea点击:

Check if an element is present in an array

javascriptarrays

提问by Francisc

The function I am using now to check this is the following:

我现在用来检查的功能如下:

function inArray(needle,haystack)
{
    var count=haystack.length;
    for(var i=0;i<count;i++)
    {
        if(haystack[i]===needle){return true;}
    }
    return false;
}

It works. What I'm looking for is whether there is a better way of doing this.

有用。我正在寻找的是是否有更好的方法来做到这一点。

回答by Alister

ECMAScript 2016incorporates an includes()method for arrays that specifically solves the problem, and so is now the preferred method.

ECMAScript 2016包含了includes()一种专门解决该问题的数组方法,因此现在是首选方法。

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array at which to begin searching)

As of JULY 2018, this has been implementedin almost all majorbrowsers, if you need to support IE a polyfillis available.

截至 2018 年 7 月,这在几乎所有主要浏览器中实现,如果您需要支持 IE,则可以使用polyfill

Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

编辑:请注意,如果数组中的项目是对象,则返回 false。这是因为相似的对象在 JavaScript 中是两个不同的对象。

回答by Benny Neugebauer

Code:

代码:

function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

Execution:

执行:

isInArray(1, [1,2,3]); // true

Update (2017):

更新(2017):

In modern browsers which follow the ECMAScript 2016 (ES7) standard, you can use the function Array.prototype.includes, which makes it way more easier to check if an item is present in an array:

在遵循 ECMAScript 2016 (ES7) 标准的现代浏览器中,您可以使用函数Array.prototype.includes,这可以更轻松地检查数组中是否存在项目:

const array = [1, 2, 3];
const value = 1;
const isInArray = array.includes(value);
console.log(isInArray); // true

回答by phihag

Just use indexOf:

只需使用indexOf

haystack.indexOf(needle) >= 0

If you want to support old Internet Explorers (< IE9), you'll have to include your current code as a workaround though.

如果您想支持旧的 Internet Explorer (< IE9),则必须包含您当前的代码作为解决方法

Unless your list is sorted, you need to compare every value to the needle. Therefore, both your solution and indexOfwill have to execute n/2comparisons on average. However, since indexOfis a built-in method, it may use additional optimizations and will be slightly faster in practice. Note that unless your application searches in lists extremely often (say a 1000 times per second) or the lists are huge (say 100k entries), the speed difference will not matter.

除非您的列表已排序,否则您需要将每个值与针进行比较。因此,您的解决方案和indexOf将不得不执行n/2平均比较。然而,由于它indexOf是一个内置方法,它可能会使用额外的优化,并且在实践中会稍微快一点。请注意,除非您的应用程序在列表中搜索非常频繁(例如每秒 1000 次)或列表很大(例如 100k 个条目),否则速度差异无关紧要。

回答by psyduck.the.apex.predator

I benchmarked it multiple times on Google Chrome 52, but feel free to copypaste it into any other browser's console.

我在 Google Chrome 52 上对其进行了多次基准测试,但可以随意将其复制粘贴到任何其他浏览器的控制台中。



~ 1500 ms, includes (~ 2700 ms when I used the polyfill)

~ 1500 毫秒,包括(当我使用polyfill时 ~ 2700 毫秒)

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(array.includes("test") === true){ result++; }
}
console.log(new Date().getTime() - start);


~ 1050 ms, indexOf

~ 1050 毫秒,索引

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(array.indexOf("test") > -1){ result++; }
}
console.log(new Date().getTime() - start);


~ 650 ms, custom function

~ 650 ms,自定义功能

function inArray(target, array)
{

/* Caching array.length doesn't increase the performance of the for loop on V8 (and probably on most of other major engines) */

  for(var i = 0; i < array.length; i++) 
  {
    if(array[i] === target)
    {
      return true;
    }
  }

  return false; 
}

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(inArray("test", array) === true){ result++; }
}
console.log(new Date().getTime() - start);

回答by Akarsh Satija

Single line code.. will return true or false

单行代码.. 将返回真或假

!!(arr.indexOf("val")+1)

回答by Akarsh Satija

You can use indexOfBut not working well in the last version of internet explorer. Code:

您可以使用indexOf但在最新版本的 Internet Explorer 中无法正常工作。 代码:

function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

Execution:

执行:

isInArray(1, [1,2,3]); // true

I suggest you use the following code:

我建议您使用以下代码:

function inArray(needle, haystack) {
 var length = haystack.length;
 for (var i = 0; i < length; i++) {
 if (haystack[i] == needle)
  return true;
 }
 return false;
}

回答by Chris Alley

You can use the _containsfunction from the underscore.js library to achieve this:

您可以使用underscore.js 库中的_contains函数来实现此目的:

if (_.contains(haystack, needle)) {
  console.log("Needle found.");
};

回答by Nicolas

Since ECMAScript6, one can use Set :

从 ECMAScript6 开始,可以使用 Set :

var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false

回答by Connor Leech

In lodash you can use _.includes(which also aliases to _.contains)

在 lodash 中你可以使用_.includes(它也是 _.contains 的别名)

You can search the whole array:

您可以搜索整个数组:

_.includes([1, 2, 3], 1); // true

You can search the array from a starting index:

您可以从起始索引搜索数组:

_.includes([1, 2, 3], 1, 1);  // false (begins search at index 1)

Search a string:

搜索字符串:

_.includes('pebbles', 'eb');  // true (string contains eb)

Also works for checking simple arrays of objects:

也适用于检查简单的对象数组:

_.includes({ 'user': 'fred', 'age': 40 }, 'fred');    // true
_.includes({ 'user': 'fred', 'age': false }, false);  // true

One thing to note about the last case is it works for primitives like strings, numbers and booleans but cannot search through arrays or objects

关于最后一种情况需要注意的一件事是它适用于字符串、数字和布尔值等基元,但不能搜索数组或对象

_.includes({ 'user': 'fred', 'age': {} }, {});   // false
_.includes({ 'user': [1,2,3], 'age': {} }, 3);   // false