This article mainly introduces the example of extending the Arraycontains method in JavaScript. This article provides the implementation code directly. if you need it, you can refer to the javascript Array without the contains method. sometimes this will be inconvenient. The contains method is easy to implement:
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 shown in the following js
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 easily use the contains method:
The code is as follows:
Alert ([1, 2, 3]. contains (2); // => true
Alert ([1, 2, 3]. contains ('2'); // => false