A method of realizing the JS function of whether an array contains an element
Array.prototype.contains = function (obj) {
var i = this.length;
while (i--) {
if (this[i] = = obj) {return
true;
}
}
return false;
}
Or
Array.prototype.contains = function (Element) {for
(var i = 0; i < this.length; i++) {
if (this[i] = = Element ) {return
true;
}
}
return false;
}
Or
Array.prototype.in_array = function (e) {for
(i=0; i<this.length && this[i]!=e; i++);
Return! (i==this.length);
}
There's another Daniel who wrote this:
ARRAY.PROTOTYPE.S = String.fromCharCode (2);
Array.prototype.in_array = function (e) {
var r = new RegExp (this. S+e+this. S);
Return (R.test) (this. S+this.join (this. S) +this. S));
}
The use method is:
var arr=["A", "B"];
Alert (Arr.in_array ("a"))
While minus iteration is said to be the fastest way in JS, do not know if it is true, from
Http://stackoverflow.com/questions/237104/javascript-array-containsobj
It's a very intense discussion here, and it's recommended to see if there is a way to use jquery, directly using jquery, refer to the address:
http://api.jquery.com/jQuery.inArray/
The above judge whether the array contains an element of the JS function implementation method is small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.