简体   繁体   English

如何检查数组是否包含 JavaScript 中的值?

[英]How do I check if an array includes a value in JavaScript?

What is the most concise and efficient way to find out if a JavaScript array contains a value?找出 JavaScript 数组是否包含值的最简洁有效的方法是什么?

This is the only way I know to do it:这是我知道的唯一方法:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

Is there a better and more concise way to accomplish this?有没有更好更简洁的方法来完成这个?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array?这与 Stack Overflow 问题Best way to find an item in a JavaScript Array?密切相关。 which addresses finding objects in an array using indexOf .它解决了使用indexOf在数组中查找对象的问题。

Modern browsers have Array#includes , which does exactly that and is widely supported by everyone except IE:现代浏览器有Array#includes ,它正是这样做的,并且得到了除 IE 之外的所有人的广泛支持

 console.log(['joe', 'jane', 'mary'].includes('jane')); //true

You can also use Array#indexOf , which is less direct, but doesn't require polyfills for outdated browsers.您也可以使用Array#indexOf ,它不那么直接,但对于过时的浏览器不需要 polyfill。

 console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true


Many frameworks also offer similar methods:许多框架也提供了类似的方法:

Notice that some frameworks implement this as a function, while others add the function to the array prototype.请注意,一些框架将其实现为一个函数,而另一些框架则将该函数添加到数组原型中。

Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. 2019 年更新:此答案来自 2008 年(11 岁!),与现代 JS 使用无关。 The promised performance improvement was based on a benchmark done in browsers of that time.承诺的性能改进是基于当时在浏览器中完成的基准测试。 It might not be relevant to modern JS execution contexts.它可能与现代 JS 执行上下文无关。 If you need an easy solution, look for other answers.如果您需要一个简单的解决方案,请寻找其他答案。 If you need the best performance, benchmark for yourself in the relevant execution environments.如果您需要最佳性能,请在相关执行环境中为自己进行基准测试。

As others have said, the iteration through the array is probably the best way, but it has been proven that a decreasing while loop is the fastest way to iterate in JavaScript.正如其他人所说,通过数组进行迭代可能是最好的方式,但已经证明递减的while循环是 JavaScript 中最快的迭代方式。 So you may want to rewrite your code as follows:所以你可能想重写你的代码如下:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

Of course, you may as well extend Array prototype:当然,你也可以扩展 Array 原型:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

And now you can simply use the following:现在您可以简单地使用以下内容:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false

indexOf maybe, but it's a "JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard." indexOf可能,但它是“ECMA-262 标准的 JavaScript 扩展;因此它可能不存在于该标准的其他实现中。”

Example:例子:

[1, 2, 3].indexOf(1) => 0
["foo", "bar", "baz"].indexOf("bar") => 1
[1, 2, 3].indexOf(4) => -1

AFAICS Microsoft does not offer some kind of alternative to this, but you can add similar functionality to arrays in Internet Explorer (and other browsers that don't support indexOf ) if you want to, as a quick Google search reveals (for example, this one ). AFAICS Microsoft没有为此提供某种替代方案,但如果您愿意,您可以在 Internet Explorer(以及其他不支持indexOf的浏览器)中为数组添加类似的功能,正如Google 快速搜索所显示的那样(例如, 这个一)。

The top answers assume primitive types but if you want to find out if an array contains an object with some trait, Array.prototype.some() is an elegant solution:最重要的答案假定原始类型,但如果你想知道一个数组是否包含一个具有某种特征的对象Array.prototype.some()是一个优雅的解决方案:

const items = [ {a: '1'}, {a: '2'}, {a: '3'} ]

items.some(item => item.a === '3')  // returns true
items.some(item => item.a === '4')  // returns false

The nice thing about it is that the iteration is aborted once the element is found so unnecessary iteration cycles are spared.它的好处是一旦找到元素就会中止迭代,这样就可以避免不必要的迭代周期。

Also, it fits nicely in an if statement since it returns a boolean:此外,它非常适合if语句,因为它返回一个布尔值:

if (items.some(item => item.a === '3')) {
  // do something
}

* As jamess pointed out in the comment, at the time of this answer, September 2018, Array.prototype.some() is fully supported: caniuse.com support table * 正如 jamess 在评论中指出的那样,在 2018 年 9 月给出这个答案时,完全支持Array.prototype.some()caniuse.com 支持表

ECMAScript 7 introduces Array.prototype.includes . ECMAScript 7 引入了Array.prototype.includes

It can be used like this:它可以这样使用:

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

It also accepts an optional second argument fromIndex :它还接受可选的第二个参数fromIndex

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

Unlike indexOf , which uses Strict Equality Comparison , includes compares using SameValueZero equality algorithm.与使用Strict Equality ComparisonindexOf不同,它includes使用SameValueZero相等算法的比较。 That means that you can detect if an array includes a NaN :这意味着您可以检测数组是否包含NaN

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

Also unlike indexOf , includes does not skip missing indices:indexOf不同的是, includes不会跳过缺失的索引:

new Array(5).includes(undefined); // true

It can be polyfilled to make it work on all browsers.可以对其进行polyfill以使其适用于所有浏览器。

Let's say you've defined an array like so:假设您已经定义了一个这样的数组:

const array = [1, 2, 3, 4]

Below are three ways of checking whether there is a 3 in there.以下是检查其中是否有3的三种方法。 All of them return either true or false .它们都返回truefalse

Native Array method (since ES2016) ( compatibility table ) Native Array 方法(自 ES2016 起)(兼容性表

array.includes(3) // true

As custom Array method (pre ES2016)作为自定义 Array 方法(ES2016 之前)

// Prefixing the method with '_' to avoid name clashes
Object.defineProperty(Array.prototype, '_includes', { value: function (v) { return this.indexOf(v) !== -1 }})
array._includes(3) // true

Simple function简单的功能

const includes = (a, v) => a.indexOf(v) !== -1
includes(array, 3) // true

Here's a JavaScript 1.6 compatible implementation of Array.indexOf :这是Array.indexOfJavaScript 1.6 兼容实现:

if (!Array.indexOf) {
    Array.indexOf = [].indexOf ?
        function(arr, obj, from) {
            return arr.indexOf(obj, from);
        } :
        function(arr, obj, from) { // (for IE6)
            var l = arr.length,
                i = from ? parseInt((1 * from) + (from < 0 ? l : 0), 10) : 0;
            i = i < 0 ? 0 : i;
            for (; i < l; i++) {
                if (i in arr && arr[i] === obj) {
                    return i;
                }
            }
            return -1;
        };
}

Use:利用:

function isInArray(array, search)
{
    return array.indexOf(search) >= 0;
}

// Usage
if(isInArray(my_array, "my_value"))
{
    //...
}

Extending the JavaScript Array object is a really bad idea because you introduce new properties (your custom methods) into for-in loops which can break existing scripts.扩展 JavaScript Array对象是一个非常糟糕的主意,因为您将新属性(您的自定义方法)引入到for-in循环中,这可能会破坏现有脚本。 A few years ago the authors of the Prototype library had to re-engineer their library implementation to remove just this kind of thing.几年前, Prototype库的作者不得不重新设计他们的库实现以删除这种东西。

If you don't need to worry about compatibility with other JavaScript running on your page, go for it, otherwise, I'd recommend the more awkward, but safer free-standing function solution.如果您不需要担心与页面上运行的其他 JavaScript 的兼容性,那就去吧,否则,我会推荐更笨拙但更安全的独立函数解决方案。

Performance表现

Today 2020.01.07 I perform tests on MacOs HighSierra 10.13.6 on Chrome v78.0.0, Safari v13.0.4 and Firefox v71.0.0 for 15 chosen solutions.今天 2020.01.07 我在 Chrome v78.0.0、Safari v13.0.4 和 Firefox v71.0.0 上对 MacOs HighSierra 10.13.6 进行了 15 种选定解决方案的测试。 Conclusions结论

  • solutions based on JSON , Set and surprisingly find (K,N,O) are slowest on all browsers基于JSONSet和意外find (K,N,O) 的解决方案在所有浏览器上最慢
  • the es6 includes (F) is fast only on chrome es6 includes (F) 仅在 chrome 上速度很快
  • the solutions based on for (C,D) and indexOf (G,H) are quite-fast on all browsers on small and big arrays so probably they are best choice for efficient solution基于for (C,D) 和indexOf (G,H) 的解决方案在大小数组上的所有浏览器上都非常快,因此它们可能是有效解决方案的最佳选择
  • the solutions where index decrease during loop, (B) is slower probably because the way of CPU cache works .循环期间索引减少的解决方案,(B) 速度较慢可能是因为CPU 缓存的工作方式。
  • I also run test for big array when searched element was on position 66% of array length, and solutions based on for (C,D,E) gives similar results (~630 ops/sec - but the E on safari and firefox was 10-20% slower than C and D)当搜索的元素位于数组长度的 66% 位置时,我还对大数组进行了测试,基于for (C,D,E) 的解决方案给出了类似的结果(~630 ops/sec - 但 safari 和 firefox 上的 E 为 10 -20% 比 C 和 D 慢)

Results结果

在此处输入图像描述

Details细节

I perform 2 tests cases: for array with 10 elements, and array with 1 milion elements.我执行 2 个测试用例:对于具有 10 个元素的数组和具有 100 万个元素的数组。 In both cases we put searched element in the array middle.在这两种情况下,我们都将搜索到的元素放在数组中间。

 let log = (name,f) => console.log(`${name}: 3-${f(arr,'s10')} 's7'-${f(arr,'s7')} 6-${f(arr,6)} 's3'-${f(arr,'s3')}`) let arr = [1,2,3,4,5,'s6','s7','s8','s9','s10']; //arr = new Array(1000000).fill(123); arr[500000]=7; function A(a, val) { var i = -1; var n = a.length; while (i++<n) { if (a[i] === val) { return true; } } return false; } function B(a, val) { var i = a.length; while (i--) { if (a[i] === val) { return true; } } return false; } function C(a, val) { for (var i = 0; i < a.length; i++) { if (a[i] === val) return true; } return false; } function D(a,val) { var len = a.length; for(var i = 0 ; i < len;i++) { if(a[i] === val) return true; } return false; } function E(a, val){ var n = a.length-1; var t = n/2; for (var i = 0; i <= t; i++) { if (a[i] === val || a[ni] === val) return true; } return false; } function F(a,val) { return a.includes(val); } function G(a,val) { return a.indexOf(val)>=0; } function H(a,val) { return !!~a.indexOf(val); } function I(a, val) { return a.findIndex(x=> x==val)>=0; } function J(a,val) { return a.some(x=> x===val); } function K(a, val) { const s = JSON.stringify(val); return a.some(x => JSON.stringify(x) === s); } function L(a,val) { return !a.every(x=> x!==val); } function M(a, val) { return !!a.find(x=> x==val); } function N(a,val) { return a.filter(x=>x===val).length > 0; } function O(a, val) { return new Set(a).has(val); } log('A',A); log('B',B); log('C',C); log('D',D); log('E',E); log('F',F); log('G',G); log('H',H); log('I',I); log('J',J); log('K',K); log('L',L); log('M',M); log('N',N); log('O',O);
 This shippet only presents functions used in performance tests - it not perform tests itself!

Array small - 10 elements小数组 - 10 个元素

You can perform tests in your machine HERE您可以在您的机器上执行测试这里

在此处输入图像描述

Array big - 1.000.000 elements大数组 - 1.000.000 个元素

You can perform tests in your machine HERE您可以在您的机器上执行测试这里

在此处输入图像描述

One-liner:单线:

function contains(arr, x) {
    return arr.filter(function(elem) { return elem == x }).length > 0;
}

Thinking out of the box for a second, if you are making this call many many times, it is vastly more efficient to use an associative array a Map to do lookups using a hash function.开箱即用,如果您多次多次进行此调用,则使用 关联数组 和 Map 使用散列函数进行查找会效率更高。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

I use the following:我使用以下内容:

Array.prototype.contains = function (v) {
    return this.indexOf(v) > -1;
}

var a = [ 'foo', 'bar' ];

a.contains('foo'); // true
a.contains('fox'); // false
function contains(a, obj) {
    return a.some(function(element){return element == obj;})
}

Array.prototype.some() was added to the ECMA-262 standard in the 5th edition Array.prototype.some()在第 5 版中被添加到 ECMA-262 标准中

If you are using JavaScript 1.6 or later (Firefox 1.5 or later) you can use Array.indexOf .如果您使用 JavaScript 1.6 或更高版本(Firefox 1.5 或更高版本),则可以使用Array.indexOf Otherwise, I think you are going to end up with something similar to your original code.否则,我认为您最终会得到类似于原始代码的内容。

A hopefully faster bidirectional indexOf / lastIndexOf alternative希望更快的双向indexOf / lastIndexOf替代方案

2015 2015

While the new method includes is very nice, the support is basically zero for now.虽然新方法includes非常好,但目前支持基本上为零。

It's a long time that I was thinking of a way to replace the slow indexOf / lastIndexOf functions.很长时间以来,我一直在想一种方法来替换缓慢的indexOf / lastIndexOf函数。

A performant way has already been found, looking at the top answers.已经找到了一种高效的方法,查看最重要的答案。 From those I chose the contains function posted by @Damir Zekic which should be the fastest one.从那些我选择了@Damir Zekic 发布的contains功能,这应该是最快的。 But it also states that the benchmarks are from 2008 and so are outdated.但它也指出,基准是从 2008 年开始的,因此已经过时。

I also prefer while over for , but for not a specific reason I ended writing the function with a for loop.我也更喜欢while不是for ,但不是出于特定原因,我结束了用 for 循环编写函数。 It could be also done with a while -- .它也可以用一段while --

I was curious if the iteration was much slower if I check both sides of the array while doing it.如果我在执行过程中检查数组的两侧,我很好奇迭代是否会慢得多。 Apparently no, and so this function is around two times faster than the top voted ones.显然没有,所以这个函数比投票最多的函数快两倍左右。 Obviously it's also faster than the native one.显然它也比原生的更快。 This is in a real world environment, where you never know if the value you are searching is at the beginning or at the end of the array.这是在真实世界环境中,您永远不知道要搜索的值是在数组的开头还是结尾。

When you know you just pushed an array with a value, using lastIndexOf remains probably the best solution, but if you have to travel through big arrays and the result could be everywhere, this could be a solid solution to make things faster.当您知道您刚刚推送了一个带有值的数组时,使用 lastIndexOf 可能仍然是最好的解决方案,但是如果您必须遍历大数组并且结果可能无处不在,这可能是使事情变得更快的可靠解决方案。

Bidirectional indexOf / lastIndexOf双向indexOf / lastIndexOf

function bidirectionalIndexOf(a, b, c, d, e){
  for(c=a.length,d=c*1; c--; ){
    if(a[c]==b) return c; //or this[c]===b
    if(a[e=d-1-c]==b) return e; //or a[e=d-1-c]===b
  }
  return -1
}

//Usage
bidirectionalIndexOf(array,'value');

Performance test性能测试

https://jsbench.me/7el1b8dj80 https://jsbench.me/7el1b8dj80

As a test I created an array with 100k entries.作为测试,我创建了一个包含 100k 条目的数组。

Three queries: at the beginning, in the middle & at the end of the array.三个查询:在数组的开头、中间和结尾。

I hope you also find this interesting and test the performance.我希望你也觉得这很有趣并测试性能。

Note: As you can see I slightly modified the contains function to reflect the indexOf & lastIndexOf output (so basically true with the index and false with -1 ).注意:如您所见,我稍微修改了contains函数以反映indexOflastIndexOf输出(因此index基本上为true-1false )。 That shouldn't harm it.那不应该伤害它。

The array prototype variant数组原型变体

Object.defineProperty(Array.prototype,'bidirectionalIndexOf',{value:function(b,c,d,e){
  for(c=this.length,d=c*1; c--; ){
    if(this[c]==b) return c; //or this[c]===b
    if(this[e=d-1-c] == b) return e; //or this[e=d-1-c]===b
  }
  return -1
},writable:false, enumerable:false});

// Usage
array.bidirectionalIndexOf('value');

The function can also be easily modified to return true or false or even the object, string or whatever it is.该函数也可以很容易地修改为返回真或假,甚至返回对象、字符串或其他任何东西。

And here is the while variant:这是while变体:

function bidirectionalIndexOf(a, b, c, d){
  c=a.length; d=c-1;
  while(c--){
    if(b===a[c]) return c;
    if(b===a[d-c]) return d-c;
  }
  return c
}

// Usage
bidirectionalIndexOf(array,'value');

How is this possible?这怎么可能?

I think that the simple calculation to get the reflected index in an array is so simple that it's two times faster than doing an actual loop iteration.我认为在数组中获取反射索引的简单计算非常简单,它比执行实际循环迭代快两倍。

Here is a complex example doing three checks per iteration, but this is only possible with a longer calculation which causes the slowdown of the code.这是一个复杂的示例,每次迭代执行三项检查,但这只有通过更长的计算才能实现,这会导致代码变慢。

https://web.archive.org/web/20151019160219/http://jsperf.com/bidirectionalindexof/2 https://web.archive.org/web/20151019160219/http://jsperf.com/bidirectionalindexof/2

function inArray(elem,array)
{
    var len = array.length;
    for(var i = 0 ; i < len;i++)
    {
        if(array[i] == elem){return i;}
    }
    return -1;
} 

Returns array index if found, or -1 if not found如果找到则返回数组索引,如果未找到则返回 -1

We use this snippet (works with objects, arrays, strings):我们使用这个片段(适用于对象、数组、字符串):

/*
 * @function
 * @name Object.prototype.inArray
 * @description Extend Object prototype within inArray function
 *
 * @param {mix}    needle       - Search-able needle
 * @param {bool}   searchInKey  - Search needle in keys?
 *
 */
Object.defineProperty(Object.prototype, 'inArray',{
    value: function(needle, searchInKey){

        var object = this;

        if( Object.prototype.toString.call(needle) === '[object Object]' || 
            Object.prototype.toString.call(needle) === '[object Array]'){
            needle = JSON.stringify(needle);
        }

        return Object.keys(object).some(function(key){

            var value = object[key];

            if( Object.prototype.toString.call(value) === '[object Object]' || 
                Object.prototype.toString.call(value) === '[object Array]'){
                value = JSON.stringify(value);
            }

            if(searchInKey){
                if(value === needle || key === needle){
                return true;
                }
            }else{
                if(value === needle){
                    return true;
                }
            }
        });
    },
    writable: true,
    configurable: true,
    enumerable: false
});

Usage:用法:

var a = {one: "first", two: "second", foo: {three: "third"}};
a.inArray("first");          //true
a.inArray("foo");            //false
a.inArray("foo", true);      //true - search by keys
a.inArray({three: "third"}); //true

var b = ["one", "two", "three", "four", {foo: 'val'}];
b.inArray("one");         //true
b.inArray('foo');         //false
b.inArray({foo: 'val'})   //true
b.inArray("{foo: 'val'}") //false

var c = "String";
c.inArray("S");        //true
c.inArray("s");        //false
c.inArray("2", true);  //true
c.inArray("20", true); //false

If you are checking repeatedly for existence of an object in an array you should maybe look into如果您反复检查数组中是否存在对象,您可能应该查看

  1. Keeping the array sorted at all times by doing insertion sort in your array (put new objects in on the right place)通过在数组中进行插入排序来保持数组始终排序(将新对象放在正确的位置)
  2. Make updating objects as remove+sorted insert operation and将对象更新为删除+排序插入操作和
  3. Use a binary search lookup in your contains(a, obj) .在您的contains(a, obj)中使用二进制搜索查找。

Solution that works in all modern browsers:适用于所有现代浏览器的解决方案:

function contains(arr, obj) {
  const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration
  return arr.some(item => JSON.stringify(item) === stringifiedObj);
}

Usage:用法:

contains([{a: 1}, {a: 2}], {a: 1}); // true

IE6+ solution: IE6+解决方案:

function contains(arr, obj) {
  var stringifiedObj = JSON.stringify(obj)
  return arr.some(function (item) {
    return JSON.stringify(item) === stringifiedObj;
  });
}

// .some polyfill, not needed for IE9+
if (!('some' in Array.prototype)) {
  Array.prototype.some = function (tester, that /*opt*/) {
    for (var i = 0, n = this.length; i < n; i++) {
      if (i in this && tester.call(that, this[i], i, this)) return true;
    } return false;
  };
}

Usage:用法:

contains([{a: 1}, {a: 2}], {a: 1}); // true

Why to use JSON.stringify ?为什么要使用JSON.stringify

Array.indexOf and Array.includes (as well as most of the answers here) only compare by reference and not by value. Array.indexOfArray.includes (以及这里的大多数答案)仅按引用而不是按值进行比较。

[{a: 1}, {a: 2}].includes({a: 1});
// false, because {a: 1} is a new object

Bonus奖金

Non-optimized ES6 one-liner:未优化的 ES6 单行:

[{a: 1}, {a: 2}].some(item => JSON.stringify(item) === JSON.stringify({a: 1));
// true

Note: Comparing objects by value will work better if the keys are in the same order, so to be safe you might sort the keys first with a package like this one: https://www.npmjs.com/package/sort-keys注意:如果键的顺序相同,按值比较对象会更好,所以为了安全起见,您可以先使用如下包对键进行排序: https ://www.npmjs.com/package/sort-keys


Updated the contains function with a perf optimization.使用 perf 优化更新了contains函数。 Thanks itinance for pointing it out.感谢itinance指出。

Use lodash's some function.使用 lodash 的一些功能。

It's concise, accurate and has great cross platform support.它简洁,准确,并具有出色的跨平台支持。

The accepted answer does not even meet the requirements.接受的答案甚至不符合要求。

Requirements: Recommend most concise and efficient way to find out if a JavaScript array contains an object.要求:推荐最简洁有效的方法来判断一个 JavaScript 数组是否包含一个对象。

Accepted Answer:接受的答案:

$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])
> -1

My recommendation:我的建议:

_.some([{'a': 1}, {'b': 2}], {'b': 2})
> true

Notes:笔记:

$.inArray works fine for determining whether a scalar value exists in an array of scalars... $.inArray 可以很好地确定量值是否存在于标量数组中...

$.inArray(2, [1,2])
> 1

... but the question clearly asks for an efficient way to determine if an object is contained in an array. ...但问题显然要求一种有效的方法来确定对象是否包含在数组中。

In order to handle both scalars and objects, you could do this:为了同时处理标量和对象,您可以这样做:

(_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1)

Simple solution for this requirement is using find()此要求的简单解决方案是使用find()

If you're having array of objects like below,如果您有如下对象数组,

var users = [{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "admin"},
{id: "105", name: "user"}];

Then you can check whether the object with your value is already present or not:然后您可以检查具有您的值的对象是否已经存在:

let data = users.find(object => object['id'] === '104');

if data is null then no admin, else it will return the existing object like:如果数据为空,则没有管理员,否则它将返回现有对象,例如:

{id: "104", name: "admin"}

Then you can find the index of that object in the array and replace the object using the code:然后您可以在数组中找到该对象的索引并使用代码替换该对象:

let indexToUpdate = users.indexOf(data);
let newObject = {id: "104", name: "customer"};
users[indexToUpdate] = newObject;//your new object
console.log(users);

you will get value like:您将获得如下价值:

[{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "customer"},
{id: "105", name: "user"}];

While array.indexOf(x)!=-1 is the most concise way to do this (and has been supported by non-Internet Explorer browsers for over decade...), it is not O(1), but rather O(N), which is terrible.虽然array.indexOf(x)!=-1是做到这一点的最简洁的方法(并且已经被非 Internet Explorer 浏览器支持了十多年......),但它不是 O(1),而是 O( N),这是可怕的。 If your array will not be changing, you can convert your array to a hashtable, then do table[x]!==undefined or ===undefined :如果您的数组不会改变,您可以将数组转换为哈希表,然后执行table[x]!==undefined===undefined

Array.prototype.toTable = function() {
    var t = {};
    this.forEach(function(x){t[x]=true});
    return t;
}

Demo:演示:

var toRemove = [2,4].toTable();
[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})

(Unfortunately, while you can create an Array.prototype.contains to "freeze" an array and store a hashtable in this._cache in two lines, this would give wrong results if you chose to edit your array later. JavaScript has insufficient hooks to let you keep this state, unlike Python for example.) (不幸的是,虽然您可以创建一个 Array.prototype.contains 来“冻结”一个数组并在 this._cache 中分两行存储一个哈希表,但如果您选择稍后编辑您的数组,这将给出错误的结果。JavaScript 没有足够的钩子来让你保持这种状态,不像 Python 例如。)

ECMAScript 6 has an elegant proposal on find. ECMAScript 6 在 find 上有一个优雅的提议。

The find method executes the callback function once for each element present in the array until it finds one where callback returns a true value. find 方法对数组中存在的每个元素执行一次回调函数,直到找到一个回调函数返回真值。 If such an element is found, find immediately returns the value of that element.如果找到这样的元素,find 立即返回该元素的值。 Otherwise, find returns undefined.否则,find 返回 undefined。 callback is invoked only for indexes of the array which have assigned values;回调仅针对已分配值的数组索引调用; it is not invoked for indexes which have been deleted or which have never been assigned values.对于已被删除或从未被赋值的索引,它不会被调用。

Here is the MDN documentation on that.这是MDN 文档

The find functionality works like this.查找功能是这样工作的。

function isPrime(element, index, array) {
    var start = 2;
    while (start <= Math.sqrt(element)) {
        if (element % start++ < 1) return false;
    }
    return (element > 1);
}

console.log( [4, 6, 8, 12].find(isPrime) ); // Undefined, not found
console.log( [4, 5, 8, 12].find(isPrime) ); // 5

You can use this in ECMAScript 5 and below by defining the function .您可以通过定义函数在 ECMAScript 5 及以下版本中使用它。

if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(predicate) {
      if (this == null) {
        throw new TypeError('Array.prototype.find called on null or undefined');
      }
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }
      var list = Object(this);
      var length = list.length >>> 0;
      var thisArg = arguments[1];
      var value;

      for (var i = 0; i < length; i++) {
        if (i in list) {
          value = list[i];
          if (predicate.call(thisArg, value, i, list)) {
            return value;
          }
        }
      }
      return undefined;
    }
  });
}

One can use Set that has the method "has()":可以使用具有“has()”方法的Set

 function contains(arr, obj) { var proxy = new Set(arr); if (proxy.has(obj)) return true; else return false; } var arr = ['Happy', 'New', 'Year']; console.log(contains(arr, 'Happy'));

Use:利用:

var myArray = ['yellow', 'orange', 'red'] ;

alert(!!~myArray.indexOf('red')); //true

Demo演示

To know exactly what the tilde ~ do at this point, refer to this question What does a tilde do when it precedes an expression?要确切地知道tilde ~在这一点上做什么,请参阅这个问题当它在表达式之前时波浪号做什么? . .

OK, you can just optimise your code to get the result!好的,你可以优化你的代码来得到结果!

There are many ways to do this which are cleaner and better, but I just wanted to get your pattern and apply to that using JSON.stringify , just simply do something like this in your case:有很多方法可以做到这一点,更干净,更好,但我只是想获得你的模式并使用JSON.stringify应用到它,只需在你的情况下做这样的事情:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (JSON.stringify(a[i]) === JSON.stringify(obj)) {
            return true;
        }
    }
    return false;
}

Surprised that this question still doesn't have latest syntax added, adding my 2 cents.惊讶于这个问题仍然没有添加最新的语法,增加了我的 2 美分。

Let's say we have array of Objects arrObj and we want to search obj in it.假设我们有一个对象数组 arrObj,我们想在其中搜索 obj。

Array.prototype.数组.原型。 indexOf -> (returns index or -1 ) is generally used for finding index of element in array. indexOf -> (返回index 或 -1 )通常用于查找数组中元素的索引。 This can also be used for searching object but only works if you are passing reference to same object.这也可以用于搜索对象,但仅在您传递对同一对象的引用时才有效。

let obj = { name: 'Sumer', age: 36 };
let arrObj = [obj, { name: 'Kishor', age: 46 }, { name: 'Rupen', age: 26 }];


console.log(arrObj.indexOf(obj));// 0
console.log(arrObj.indexOf({ name: 'Sumer', age: 36 })); //-1

console.log([1, 3, 5, 2].indexOf(2)); //3

Array.prototype.数组.原型。 includes -> (returns true or false )包括-> (返回truefalse

console.log(arrObj.includes(obj));  //true
console.log(arrObj.includes({ name: 'Sumer', age: 36 })); //false

console.log([1, 3, 5, 2].includes(2)); //true

Array.prototype.数组.原型。 find -> (takes callback, returns first value/object that returns true in CB). find ->(接受回调,返回第一个在 CB 中返回 true 的值/对象)。

console.log(arrObj.find(e => e.age > 40));  //{ name: 'Kishor', age: 46 }
console.log(arrObj.find(e => e.age > 40)); //{ name: 'Kishor', age: 46 }

console.log([1, 3, 5, 2].find(e => e > 2)); //3

Array.prototype.数组.原型。 findIndex -> (takes callback, returns index of first value/object that returns true in CB). findIndex ->(接受回调,返回 CB 中返回 true 的第一个值/对象的索引)。

console.log(arrObj.findIndex(e => e.age > 40));  //1
console.log(arrObj.findIndex(e => e.age > 40)); //1

console.log([1, 3, 5, 2].findIndex(e => e > 2)); //1

Since find and findIndex takes a callback, we can be fetch any object(even if we don't have the reference) from array by creatively setting the true condition.由于 find 和 findIndex 接受回调,我们可以通过创造性地设置 true 条件从数组中获取任何对象(即使我们没有引用)。

It has one parameter: an array numbers of objects.它有一个参数:一组对象数。 Each object in the array has two integer properties denoted by x and y.数组中的每个对象都有两个整数属性,分别用 x 和 y 表示。 The function must return a count of all such objects in the array that satisfy numbers.x == numbers.y该函数必须返回数组中满足numbers.x == numbers.y的所有此类对象的计数

 var numbers = [ { x: 1, y: 1 }, { x: 2, y: 3 }, { x: 3, y: 3 }, { x: 3, y: 4 }, { x: 4, y: 5 } ]; var count = 0; var n = numbers.length; for (var i =0;i<n;i++) { if(numbers[i].x==numbers[i].y) {count+=1;} } alert(count);

 function countArray(originalArray) { var compressed = []; // make a copy of the input array var copyArray = originalArray.slice(0); // first loop goes over every element for (var i = 0; i < originalArray.length; i++) { var count = 0; // loop over every element in the copy and see if it's the same for (var w = 0; w < copyArray.length; w++) { if (originalArray[i] == copyArray[w]) { // increase amount of times duplicate is found count++; // sets item to undefined delete copyArray[w]; } } if (count > 0) { var a = new Object(); a.value = originalArray[i]; a.count = count; compressed.push(a); } } return compressed; }; // It should go something like this: var testArray = new Array("dog", "dog", "cat", "buffalo", "wolf", "cat", "tiger", "cat"); var newArray = countArray(testArray); console.log(newArray);

use Array.prototype.includes for example:使用Array.prototype.includes例如:

 const fruits = ['coconut', 'banana', 'apple'] const doesFruitsHaveCoconut = fruits.includes('coconut')// true console.log(doesFruitsHaveCoconut)

maybe read this documentation from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes也许从 MDN 阅读此文档: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Here's how Prototype does it :下面是Prototype 的做法

/**
 *  Array#indexOf(item[, offset = 0]) -> Number
 *  - item (?): A value that may or may not be in the array.
 *  - offset (Number): The number of initial items to skip before beginning the
 *      search.
 *
 *  Returns the position of the first occurrence of `item` within the array &mdash; or
 *  `-1` if `item` doesn't exist in the array.
**/
function indexOf(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
}

Also see here for how they hook it up.另请参阅此处了解他们如何连接它。

By no means the best, but I was just getting creative and adding to the repertoire.绝不是最好的,但我只是在发挥创造力并添加到曲目中。

Do not use this不要使用这个

 Object.defineProperty(Array.prototype, 'exists', { value: function(element, index) { var index = index || 0 return index === this.length ? -1 : this[index] === element ? index : this.exists(element, ++index) } }) // Outputs 1 console.log(['one', 'two'].exists('two')); // Outputs -1 console.log(['one', 'two'].exists('three')); console.log(['one', 'two', 'three', 'four'].exists('four'));

  1. Either use Array.indexOf(Object) .要么使用Array.indexOf(Object)
  2. With ECMA 7 one can use the Array.includes(Object) .使用 ECMA 7 可以使用Array.includes(Object)
  3. With ECMA 6 you can use Array.find(FunctionName) where FunctionName is a user defined function to search for the object in the array.使用 ECMA 6,您可以使用Array.find(FunctionName)其中FunctionName是用户定义的函数来搜索数组中的对象。

    Hope this helps!希望这可以帮助!

Use indexOf()使用 indexOf()

You can use the indexOf() method to check whether a given value or element exists in an array or not.您可以使用 indexOf() 方法检查给定值或元素是否存在于数组中。 The indexOf() method returns the index of the element inside the array if it is found, and returns -1 if it not found. indexOf() 方法如果找到则返回数组内元素的索引,如果未找到则返回 -1。 Let's take a look at the following example:让我们看一下下面的例子:

 var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; var a = "Mango"; checkArray(a, fruits); function checkArray(a, fruits) { // Check if a value exists in the fruits array if (fruits.indexOf(a) !== -1) { return document.write("true"); } else { return document.write("false"); } }

Use include() Method使用 include() 方法

ES6 has introduced the includes() method to perform this task very easily. ES6 引入了 includes() 方法来非常容易地执行此任务。 But, this method returns only true or false instead of index number:但是,此方法仅返回 true 或 false 而不是索引号:

 var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; alert(fruits.includes("Banana")); // Outputs: true alert(fruits.includes("Coconut")); // Outputs: false alert(fruits.includes("Orange")); // Outputs: true alert(fruits.includes("Cherry")); // Outputs: false

For further reference checkout here如需进一步参考,请在此处结帐

There are a couple of method which makes this easy to achieve ( includes , some , find , findIndex )有几种方法可以轻松实现( includessomefind 、查找findIndex

 const array = [1, 2, 3, 4, 5, 6, 7]; console.log(array.includes(3)); //includes() determines whether an array includes a certain value among its entries console.log(array.some(x => x === 3)); //some() tests if at least one element in the array passes the test implemented by the provided function console.log(array.find(x => x === 3) ? true : false); //find() returns the value of the first element in the provided array that satisfies the provided testing function console.log(array.findIndex(x => x === 3) > -1); //findIndex() returns the index of the first element in the array that satisfies the provided testing function, else returning -1.

You can also use this trick:你也可以使用这个技巧:

var arrayContains = function(object) {
  return (serverList.filter(function(currentObject) {
    if (currentObject === object) {
      return currentObject
    }
    else {
      return false;
    }
  }).length > 0) ? true : false
}

As others have mentioned you can use Array.indexOf , but it isn't available in all browsers.正如其他人提到的,您可以使用Array.indexOf ,但并非在所有浏览器中都可用。 Here's the code from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf to make it work the same in older browsers.这是来自https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf的代码,以使其在旧浏览器中的工作方式相同。

indexOf is a recent addition to the ECMA-262 standard; indexOf 是 ECMA-262 标准的最新补充; as such it may not be present in all browsers.因此,它可能不会出现在所有浏览器中。 You can work around this by inserting the following code at the beginning of your scripts, allowing use of indexOf in implementations which do not natively support it.您可以通过在脚本开头插入以下代码来解决此问题,允许在本机不支持它的实现中使用 indexOf。 This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.max have their original value.该算法正是 ECMA-262 第 5 版中指定的算法,假设 Object、TypeError、Number、Math.floor、Math.abs 和 Math.max 具有其原始值。

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (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 > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                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;
    }
}

Or this solution:或者这个解决方案:

Array.prototype.includes = function (object) {
  return !!+~this.indexOf(object);
};

Using idnexOf() it is a good solution, but you should hide embedded implementation indexOf() function which returns -1 with ~ operator:使用 idnexOf() 是一个很好的解决方案,但您应该隐藏嵌入式实现 indexOf() 函数,该函数使用 ~ 运算符返回 -1:

function include(arr,obj) { 
    return !!(~arr.indexOf(obj)); 
} 

I was working on a project that I needed a functionality like python set which removes all duplicates values and returns a new list, so I wrote this function maybe useful to someone我正在做一个项目,我需要一个像 python set这样的功能,它可以删除所有重复值并返回一个新列表,所以我写了这个函数可能对某人有用

function set(arr) {
    var res = [];
    for (var i = 0; i < arr.length; i++) {
        if (res.indexOf(arr[i]) === -1) {
            res.push(arr[i]);
        }
    }
    return res;
}

If you're working with ES6 You can use a set:如果您使用的是 ES6,您可以使用一组:

function arrayHas( array, element ) {
    const s = new Set(array);
    return s.has(element)
}

This should be more performant than just about any other method这应该比任何其他方法都更高效

I recommended to use underscore library because its return the value and its supported for all browsers.我建议使用下划线库,因为它返回值并支持所有浏览器。

underscorejs下划线

 var findValue = _.find(array, function(item) {
    return item.id == obj.id;
 });

In Addition to what others said, if you don't have a reference of the object which you want to search in the array, then you can do something like this.除了其他人所说的之外,如果您没有要在数组中搜索的对象的引用,那么您可以执行类似的操作。

let array = [1, 2, 3, 4, {"key": "value"}];

array.some((element) => JSON.stringify(element) === JSON.stringify({"key": "value"})) // true

array.some((element) => JSON.stringify(element) === JSON.stringify({})) // true

Array.some returns true if any element matches the given condition and returns false if none of the elements matches the given condition.如果任何元素与给定条件匹配,则 Array.some 返回 true,如果没有任何元素与给定条件匹配,则返回 false。

Object.keys for getting all property names of the object and filter all values that exact or partial match with specified string. Object.keys用于获取对象的所有属性名称并过滤与指定字符串完全或部分匹配的所有值。

 function filterByValue(array, string) { return array.filter(o => Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase()))); } const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }]; console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}] console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]

You can also filter by specific key such as.您还可以按特定键进行过滤,例如。

Object.keys(o).some(k => o.country.toLowerCase().includes(string.toLowerCase())));

Now you can just check array count after filtered to check value contains or not.现在您可以在过滤后检查数组计数以检查值是否包含。

Hope it's helpful.希望它有帮助。

Adding a unique item to a another list将唯一项目添加到另一个列表

searchResults: [
                {
                    name: 'Hello',
                    artist: 'Selana',
                    album: 'Riga',
                    id: 1,
                },
                {
                    name: 'Hello;s',
                    artist: 'Selana G',
                    album: 'Riga1',
                    id: 2,
                },
                {
                    name: 'Hello2',
                    artist: 'Selana',
                    album: 'Riga11',
                    id: 3,
                }
            ],
            playlistTracks: [
              {
                name: 'Hello',
                artist: 'Mamunuus',
                album: 'Riga',
                id: 4,
              },
              {
                name: 'Hello;s',
                artist: 'Mamunuus G',
                album: 'Riga1',
                id: 2,
              },
              {
                name: 'Hello2',
                artist: 'Mamunuus New',
                album: 'Riga11',
                id: 3,
              }
            ],
            playlistName: "New PlayListTrack",
        };
    }

    // Adding an unique track in the playList
    addTrack = track => {
      if(playlistTracks.find(savedTrack => savedTrack.id === track.id)) {
        return;
      }
      playlistTracks.push(track);

      this.setState({
        playlistTracks
      })
    };

This may be a detailed and easy solution.这可能是一个详细而简单的解决方案。

//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
   // value exists in array
   //write some codes
}

// array with objects
var arr = [
      {x:'a', y:'b'},
      {x:'p', y:'q'}
  ];

// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// or y:'q' exists in arr
var check = arr.filter(function (elm){
    if (elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p' && elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// in all cases
console.log(check.length); // returns 1

if (check.length > 0)
{
   // returns true
   // object exists in array
   //write some codes
}

The best default method to check if value exist in array JavaScript is some()检查数组 JavaScript 中是否存在值的最佳默认方法是some()

Array.prototype.some() Array.prototype.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. some()方法测试数组中的至少一个元素是否通过了提供的函数实现的测试。 It returns true if, in the array, it finds an element for which the provided function returns true;如果在数组中找到所提供函数为其返回 true 的元素,则返回 true; otherwise it returns false.否则返回false。 It doesn't modify the array.它不会修改数组。

const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

The some method is the best one in Browser compatibility some方法是浏览器兼容性最好的方法浏览器兼容性

For more documentation Array.prototype.some() - JavaScript |更多文档Array.prototype.some() - JavaScript | MDN MDN

Also you can use other two method is find() and includes() .您也可以使用其他两种方法find()includes() with those method you can get your result but not the best one.使用这些方法,您可以获得结果,但不是最好的。

Array.prototype.find() - JavaScript | Array.prototype.find() - JavaScript | MDN MDN

Array.prototype.includes() - JavaScript | Array.prototype.includes() - JavaScript | MDN MDN

Use:利用:

Array.prototype.contains = function(x){
  var retVal = -1;

  // x is a primitive type
  if(["string","number"].indexOf(typeof x)>=0 ){ retVal = this.indexOf(x);}

  // x is a function
  else if(typeof x =="function") for(var ix in this){
    if((this[ix]+"")==(x+"")) retVal = ix;
  }

  //x is an object...
  else {
    var sx=JSON.stringify(x);
    for(var ix in this){
      if(typeof this[ix] =="object" && JSON.stringify(this[ix])==sx) retVal = ix;
    }
  }

  //Return False if -1 else number if numeric otherwise string
  return (retVal === -1)?false : ( isNaN(+retVal) ? retVal : +retVal);
}

I know it's not the best way to go, but since there is no native IComparable way to interact between objects, I guess this is as close as you can get to compare two entities in an array.我知道这不是最好的方法,但是由于没有原生的 IComparable 方式来在对象之间进行交互,我想这与比较数组中的两个实体一样接近。 Also, extending Array object might not be a wise thing to do, but sometimes it's OK (if you are aware of it and the trade-off).此外,扩展 Array 对象可能不是明智之举,但有时也可以(如果您意识到这一点并进行权衡)。

I looked through submitted answers and got that they only apply if you search for the object via reference.我查看了提交的答案,发现它们仅在您通过参考搜索对象时适用。 A simple linear search with reference object comparison.带有参考对象比较的简单线性搜索。

But lets say you don't have the reference to an object, how will you find the correct object in the array?但是假设您没有对对象的引用,您将如何在数组中找到正确的对象? You will have to go linearly and deep compare with each object.您将不得不对每个对象进行线性和深度比较。 Imagine if the list is too large, and the objects in it are very big containing big pieces of text.想象一下,如果列表太大,并且其中的对象非常大,包含大量文本。 The performance drops drastically with the number and size of the elements in the array.性能随着数组中元素的数量和大小而急剧下降。

You can stringify objects and put them in the native hash table, but then you will have data redundancy remembering these keys cause JavaScript keeps them for 'for i in obj', and you only want to check if the object exists or not, that is, you have the key.您可以对对象进行字符串化并将它们放入本机哈希表中,但是您将有数据冗余记住这些键,因为 JavaScript 将它们保留为“for i in obj”,并且您只想检查对象是否存在,即,你有钥匙。

I thought about this for some time constructing a JSON Schema validator, and I devised a simple wrapper for the native hash table, similar to the sole hash table implementation, with some optimization exceptions which I left to the native hash table to deal with.我考虑了一段时间来构建一个 JSON Schema 验证器,我为本地哈希表设计了一个简单的包装器,类似于唯一的哈希表实现,但有一些优化异常,我留给本地哈希表处理。 It only needs performance benchmarking... All the details and code can be found on my blog: http://stamat.wordpress.com/javascript-quickly-find-very-large-objects-in-a-large-array/ I will soon post benchmark results.它只需要性能基准测试......所有细节和代码都可以在我的博客上找到:http: //stamat.wordpress.com/javascript-quickly-find-very-large-objects-in-a-large-array/我将很快发布基准测试结果。

The complete solution works like this:完整的解决方案是这样工作的:

var a = {'a':1,
 'b':{'c':[1,2,[3,45],4,5],
 'd':{'q':1, 'b':{'q':1, 'b':8},'c':4},
 'u':'lol'},
 'e':2};

 var b = {'a':1, 
 'b':{'c':[2,3,[1]],
 'd':{'q':3,'b':{'b':3}}},
 'e':2};

 var c = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

 var hc = new HashCache([{a:3, b:2, c:5}, {a:15, b:2, c:'foo'}]); //init

 hc.put({a:1, b:1});
 hc.put({b:1, a:1});
 hc.put(true);
 hc.put('true');
 hc.put(a);
 hc.put(c);
 hc.put(d);
 console.log(hc.exists('true'));
 console.log(hc.exists(a));
 console.log(hc.exists(c));
 console.log(hc.exists({b:1, a:1}));
 hc.remove(a);
 console.log(hc.exists(c));

Similar thing: Finds the first element by a "search lambda":类似的事情:通过“搜索 lambda”查找第一个元素:

Array.prototype.find = function(search_lambda) {
  return this[this.map(search_lambda).indexOf(true)];
};

Usage:用法:

[1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })
=> 4

Same in coffeescript:在咖啡脚本中相同:

Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)]

Simple solution : ES6 Features " includes " method简单的解决方案:ES6 Features " includes " 方法

let arr = [1, 2, 3, 2, 3, 2, 3, 4];

  arr.includes(2) // true

  arr.includes(93) // false

There are several ways to find out.有几种方法可以找出答案。 You can use inbuilt Array methods.您可以使用内置的数组方法。 The most prominently used is Array find method.最常用的是数组查找方法。

const arr1 = [1, 2, 3, 4, 5]
const result = arr1.find(ele => ele === 4)
console.log(result) //4

const result2 = arr1.find(ele => ele === 6)
console.log(result2) //undefined
/* 
If the element is present inside the array
then it will return the first element that
satisfies the given condition. Otherwise
undefined will return.
*/

You can use findIndex function to check if an array has a specific value.您可以使用 findIndex 函数来检查数组是否具有特定值。

arrObj.findIndex(obj => obj === comparedValue) !== -1;

Returns true if arrObj contains comparedValue, false otherwise.如果 arrObj 包含 compareValue,则返回 true,否则返回 false。

使用正则表达式:

console.log(new RegExp('26242').test(['23525', '26242', '25272'].join(''))) // true

If you're just trying to check whether a value is included in a collection, It would be more appropriate to use a Set , As Arrays can have duplicate values whereas Sets cannot.如果您只是想检查一个值是否包含在集合中,使用Set会更合适,因为Arrays可以有重复的值,而Sets不能。 Also, Replacing array.includes with set.has improves the performance from O(n 2 ) to O(n).此外,用set.has替换array.includes将性能从 O(n 2 ) 提高到 O(n)。 This will be useful when you have to look up multiple values for the same Set.当您必须为同一个 Set 查找多个值时,这将很有用。 so if you're just going to look up a single value, there's no benefit to use set.has , you can just use an array.includes .因此,如果您只想查找单个值,则使用set.has没有任何好处,您可以只使用array.includes

Created a jsbench demo, You can run this to check the performance.创建了一个jsbench演示,您可以运行它来检查性能。

Screenshot of the test execution :测试执行截图

在此处输入图像描述

The fastest method in Javascript to find if an array contains a value is this: Javascript 中查找数组是否包含值的最快方法是:

function existsInArrayForIgnoreDataType(arr, targetElem) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == targetElem) return true
  }
  return false
 }

You can find the complete study I did here .您可以在此处找到我所做的完整研究。

let isExistOrNot = (arr, element)=>{
    return arr.includes(element);
    // includes check that an element is included or not in an array
    // it return a boolean value true or false
}

let array = ['apple', 'ball', 'cat', 'dog']

console.log(isExistOrNot(array, 'yellow'));
//Result false because yellow doesn't exist in array
console.log(isExistOrNot(array, 'apple'));
//Result true because yellow exist in array

Literally:字面上地:

(using Firefox v3.6, with for-in caveats as previously noted (HOWEVER the use below might endorse for-in for this very purpose! That is, enumerating array elements that ACTUALLY exist via a property index (HOWEVER, in particular, the array length property is NOT enumerated in the for-in property list!).).) (使用 Firefox v3.6,带有前面提到的for-in警告(但是,出于这个目的,下面的使用可能会支持for-in !也就是说,通过属性索引枚举实际存在的数组元素(但是,特别是数组length属性未在for-in属性列表中枚举!)。)。)

(Drag & drop the following complete URI's for immediate mode browser testing.) (拖放以下完整 URI 以进行即时模式浏览器测试。)

JavaScript: JavaScript:

  function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}

  function check(ra){
      return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')
  }
  alert([
            check([{}]), check([]), check([,2,3]),
            check(['']), '\t (a null string)', check([,,,])
        ].join('\n'));

which displays:显示:

There is an object in [[object Object]].
There is NO object in [].
There is an object in [,2,3].
There is an object in [].
     (a null string)
There is NO object in [,,].

Wrinkles: if looking for a "specific" object consider:皱纹:如果寻找“特定”对象,请考虑:

JavaScript: alert({}!={}); alert({}!=={}); JavaScript: alert({}!={}); alert({}!=={}); alert({}!={}); alert({}!=={});

And thus:因此:

JavaScript: JavaScript:

 obj = {prop:"value"}; 
 ra1 = [obj]; 
 ra2 = [{prop:"value"}];
 alert(ra1[0] == obj); 
 alert(ra2[0] == obj);

Often ra2 is considered to "contain" obj as the literal entity {prop:"value"} .通常ra2被认为“包含” obj作为文字实体{prop:"value"}

A very coarse, rudimentary, naive (as in code needs qualification enhancing) solution:一个非常粗略、基本、幼稚(如代码需要资格增强)的解决方案:

JavaScript: JavaScript:

  obj={prop:"value"};   ra2=[{prop:"value"}];
  alert(
    ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?
      'found' :
      'missing' );

See ref: Searching for objects in JavaScript arrays .请参阅参考: 在 JavaScript 数组中搜索对象

Just another option只是另一种选择

// usage: if ( ['a','b','c','d'].contains('b') ) { ... }
Array.prototype.contains = function(value){
    for (var key in this)
        if (this[key] === value) return true;
    return false;
}

Be careful because overloading javascript array objects with custom methods can disrupt the behavior of other javascripts, causing unexpected behavior.请小心,因为使用自定义方法重载 javascript 数组对象可能会破坏其他 javascript 的行为,从而导致意外行为。

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

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