日期:2014-05-16 浏览次数:20440 次
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> Array.prototype.Contains = function (obj) { if (this == null || this.length <= 0) { return false; } var count = 0; for (var i = 0; i < this.length; i++) { if (this[i] == obj) { count++; } } return count > 0; } Array.prototype.Distinct = function () { if (this.length == 0) { return this; } var array = []; for (var i = 0; i < this.length; i++) { if (array.Contains(this[i]) == false) { array.push(this[i]); } } return array; } var a = new Array("0", "1", "0", "0", "2"); alert(a.join()); alert(a.Distinct().join()); </script> </head> <body> </body> </html>
------解决方案--------------------
楼上代码调整格式的时候错了一行,修正如下:
Array.prototype.distinct = function () { var a = [], b = []; for (var i = 0; i < this.length; i++) { if (b[this[i]] != 1) { a.push(this[i]); b[this[i]] = 1; } } return a; }