一.方法一
Array.prototype.unique = function(){ var arr = []; for(var i=0;i<this.length;i++){ if(arr.indexOf(this[i])==-1){ arr.push(this[i]); } } return arr; }
var arr1 = [1,2,3,5,1,2,3,5,1,2,8,9]; console.log(arr1);//[1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 8, 9] console.log(arr1.unique());//[1, 2, 3, 5, 8, 9]
二.方法二
Array.prototype.unique = function(){ this.sort(); var arr = [this[0]]; for(var i=1;i<this.length;i++){ if(this[i]!==arr[arr.length-1]){ arr.push(this[i]); } } return arr; }
var arr1 = [1,2,3,5,1,2,3,5,1,2,8,9]; console.log(arr1);//[1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 8, 9] console.log(arr1.unique());//[1, 2, 3, 5, 8, 9]