How do I check if an array includes an object in JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

What is the most concise and efficient way to find out if a JavaScript array contains an object?

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?

http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array

Answers

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill

http://api.jquery.com/jquery.inarray/ http://api.jquery.com/jquery.inarray/

http://underscorejs.org/#indexOf http://underscorejs.org/#indexOf

Some other frameworks offer similar methods:

Notice that some frameworks implement this as a function, while others add the function to the array prototype.

Languages that compile to JavaScript

http://coffeescript.org/#try:a%20%3D%20[1%2C%202%2C%203%2C%204]%0Aalert%282%20in%20a%29 http://coffeescript.org/#try:a%20%3D%20[1%2C%202%2C%203%2C%204]%0Aalert%282%20in%20a%29

a = [1, 2, 3, 4]
alert(2 in a)

http://www.dartlang.org/docs/dart-up-and-running/ch03.html#ch03-collections http://www.dartlang.org/docs/dart-up-and-running/ch03.html#ch03-collections

var mylist = [1, 2, 3];
assert(mylist.contains(1));
assert(mylist.indexOf(1) == 0);

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils