第一種是比較常規的方法html
思路:json
1.構建一個新的數組存放結果數組
2.for循環中每次從原數組中取出一個元素,用這個元素循環與結果數組對比post
3.若結果數組中沒有該元素,則存到結果數組中this
Array.prototype.unique1 = function(){
var res = [this[0]];
for(var i = 1; i < this.length; i++){
var repeat = false;
for(var j = 0; j < res.length; j++){
if(this[i] == res[j]){
repeat = true;
break;
}
}
if(!repeat){
res.push(this[i]);
}
}
return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
alert(arr.unique1());
第二種方法比上面的方法效率要高url
思路:prototype
1.先將原數組進行排序code
2.檢查原數組中的第i個元素 與 結果數組中的最後一個元素是否相同,由於已經排序,因此重複元素會在相鄰位置htm
3.若是不相同,則將該元素存入結果數組中對象
Array.prototype.unique2 = function(){
this.sort(); //先排序
var res = [this[0]];
for(var i = 1; i < this.length; i++){
if(this[i] !== res[res.length - 1]){
res.push(this[i]);
}
}
return res;
}
var arr = [1, 'a', 'a', 'b', 'd', 'e', 'e', 1, 0]
alert(arr.unique2());
第二種方法也會有必定的侷限性,由於在去重前進行了排序,因此最後返回的去重結果也是排序後的。若是要求不改變數組的順序去重,那這種方法便不可取了。
第三種方法(推薦使用)
思路:
1.建立一個新的數組存放結果
2.建立一個空對象
3.for循環時,每次取出一個元素與對象進行對比,若是這個元素不重複,則把它存放到結果數組中,同時把這個元素的內容做爲對象的一個屬性,並賦值爲1,存入到第2步創建的對象中。
說明:至於如何對比,就是每次從原數組中取出一個元素,而後到對象中去訪問這個屬性,若是能訪問到值,則說明重複。
Array.prototype.unique3 = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}
var arr = [112,112,34,'你好',112,112,34,'你好','str','str1'];alert(arr.unique3());