Js function implementation method to determine whether an array contains an element. array js
Js function implementation method for determining 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);}
Another Daniel wrote the following:
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 usage is as follows:
Var arr = ["a", "B"];
Alert (arr. in_array (""))
It is said that while subtraction iteration is the fastest method in js. I don't know if it is true.
Http://stackoverflow.com/questions/237104/javascript-array-containsobj
The discussion here is very intense. We suggest you check it out. If jQuery is used, you can directly use the method implemented by jQuery. refer:
Http://api.jquery.com/jQuery.inArray/
The js function implementation method used to determine whether the array contains an element is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the help house.