Javascript's Array does not have a contains method, which is sometimes inconvenient. The contains method is very simple to implement:
function contains(a, obj) {
var i = a.length;
while (i--) {
If (a[i] === obj) {
return true;
}
}
Return false;
}
Of course we can also extend the Array class, as follows js
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
If (this[i] === obj) {
return true;
}
}
Return false;
}
In this way, you can use the contains method conveniently:
alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false