Home >Web Front-end >JS Tutorial >Extended Array contains method instance in JavaScript_javascript skills

Extended Array contains method instance in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:09:051216browse

Javascript's Array does not have a contains method, which is sometimes inconvenient. The contains method is very simple to implement:

Copy code The code 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
Copy code The code is as follows:

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:
Copy code The code is as follows:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn