How to check if an array contains a value in JavaScript?
P粉592085423
2023-08-23 11:09:10
<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>
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:Of course, you can also extend the Array prototype:
Now you can simply use the following:
Modern browsers have
Array#includes
which do exactly that and are widely used by everyone except IE support: