JavaScript's Array does not contain the method, sometimes this is inconvenient, and the implementation of the contains method is very simple:
The code copy is as follows:
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
The code copy is as follows:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
This allows you to use the contains method conveniently:
The code copy is as follows:
alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false