P粉7885713162023-08-24 00:43:22
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粉0769873862023-08-24 00:14:12
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