How to check if an array contains a value in JavaScript?
P粉592085423
P粉592085423 2023-08-23 11:09:10
0
2
412
<p>What is the cleanest, most efficient way to find out whether a JavaScript array contains a value? </p> <p>This is the only way I know:</p> <pre class="brush:php;toolbar:false;">function contains(a, obj) { for (var i = 0; i < a.length; i ) { if (a[i] === obj) { return true; } } return false; }</pre> <p>Is there a better, cleaner way to achieve this? </p> <p>This is related to the Stack Overflow question <em>What is the best way to find items in a JavaScript array? </em> Closely related, this question addresses finding objects in an array using <code>indexOf</code>. </p>
P粉592085423
P粉592085423

reply all(2)
P粉788571316

2019 Update: This answer is from 2008 (11 years old!) and has nothing to do with modern JS usage. Promised performance improvements are based on benchmark testing completed in the browser at that time. It may not be relevant to modern JS execution context. If you need a simple solution, look for other answers. If you need the best performance, benchmark yourself in a relevant execution environment.

As others have said, iterating through an array is probably the best way to do it, but it has been proven that a descending while loop is the fastest way to iterate in JavaScript . Therefore, you may need to rewrite the code as follows:

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

Of course, you can also extend the Array prototype:

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

Now you can simply use the following:

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

Modern browsers have Array#includes which do exactly that and are widely used by everyone except IE support:

console.log(['joe', 'jane', 'mary'].includes('jane')); // true
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!