方法一
function toAgaing(){ var result = [], flag = false; for(var i = 0; i < this.length; i++){ if(this[i] !=this[i]){ if(flag){ continue; }else{ flag = true; result.push(this[i]); } }else if(result.indexOf(this[i]) == -1){ result.push(this[i]); } } return result; } Array.prototype.again = toAgaing; var x = new Array(1,1,2,2,3,3,4,4,5); console.log(x.again());
方法二
function Again(){ var res = []; for(var i = 0 ; i < this.length; i++){ var flag = false; for(var j = 0; j < res.length; j ++){ if(this[i] == res[j]){ flag = true; break; } } if(!flag){ res.push(this[i]); } } return res; } Array.prototype.toAgaing = Again; var x = new Array(1,1,2,2,3,3,4,4,5); console.log(x.toAgaing());
方法三
function Again(){ this.sort(); var res = []; for (var i = 0; i < this.length; i++) { if(this[i] != res[res.length - 1]){ res.push(this[i]); } } return res; } Array.prototype.toAgaing = Again; var x = new Array(1,1,2,2,3,3,4,4,5); console.log(x.toAgaing());
方法四
function Again(){ var res = [], obj = {}; for (var i = 0; i < this.length; i++) { if(!obj[this[i]]){ res.push(this[i]); obj[this[i]] = 1; } } return res; } Array.prototype.toAgaing = Again; var x = new Array(1,1,2,2,3,3,4,4,5); console.log(x.toAgaing());