Home > Web Front-end > JS Tutorial > body text

Extended Array contains method instance in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:09:05
Original
1202 people have browsed it

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
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template