1、用數組的 indexO方法檢測數組
function unique(arr) {this
var arr1 = [];prototype
for (var i = 0; i < arr.length; i++){對象
if (arr1.indexOf(arr[i]) === -1){io
arr1.push(arr[i]);function
}兼容性
}方法
return arr1;兼容
}push
考慮 indexOf 的兼容性, 實現Array.prototype.indexOf:
Array.prototype.indexOf = Array.prototype.indexOf || function(searchElement, fromIndex){
//是否傳入第二個參數,以及傳入的第二個參數爲負數
fromIndex = fromIndex || 0;
if( fromIndex < 0 ){
fromIndex += this.length;
if( fromIndex < 0 ){
fromIndex = 0;
}
}
for( ; fromIndex < this.length; fromIndex++){
if(this[fromIndex] === searchElement){
return fromIndex;
}
}
return -1;
}
2、利用對象鍵值判斷 (不能正確解析 1與 '1')
function unique1(arr){
var obj = {}, arr1 = [];
for(var i = 0; i < arr.length; i++){
if(!obj.hasOwnProperty(arr[i])){
obj[arr[i]] = true;
arr1.push(arr[i]);
}
}
return arr1;
}
3、ES6中的Array.from() 以及 new Set()
function unique2(arr){
return Array.from(new Set(arr));
}