Some useful examples of prototyping functions in javascript. As well as an efficient method of searching the contents of an an array for a particular value.
From http://stackoverflow.com/questions/237104/javascript-array-containsobj thanks to Damir.
As others have said, the iteration through the array is probably the best way, but it has been proven that decreasing while loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:
1 2 3 4 5 6 7 8 9
| 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:
1 2 3 4 5 6 7 8 9
| 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:
1 2
| alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false |