Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; } 或 Array.prototype.contains = function(element) { for (var i = 0; i < this.length; i++) { if (this[i] == element) { return true; } } return false; } 或 Array.prototype.in_array = function(e) { for(i=0; i<this.length && this[i]!=e; i++); return !(i==this.length); } 还有一个大牛是这样写的: 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)); }
使用方法就是:
var arr=["a","b"];
alert(arr.in_array("a"))
据说while减迭代是js里最快的一种方法,不知道是不是真的,出自
http://stackoverflow.com/questions/237104/javascript-array-containsobj
这里讨论的很激烈,建议去看看,如果有使用jQuery的话,直接使用jQuery实现的方法,参考地址:
http://api.jquery.com/jQuery.inArray/