原生js
var arr1 = [1, 1, '1', '1'];
function unique(arr) {
// res用来存储结果
var res = [];
for (var i = 0, Len = arr.length; i < Len; i++) {
for (var j = 0, resLen = res.length; j < resLen; j++ ) {
if (arr[i] === res[j]) {
break;
}
}
// 如果array[i]是唯一的,那么执行完循环,j等于resLen
if (j === resLen) {
res.push(arr[i])
}
}
return res;
}
console.log(unique(arr1)); // [1, "1"]
利用indexOf
function unique(arr) {
let res = [];
for (let i = 0, len = arr.length; i < len; i++) {
var current = arr[i];
if (res.indexOf(current) ===-1)){
res.push(current);
}
}
return res;
}
console.log(unique(arr1));
利用filter()方法
var arr2= [1, 2, 1, 1, '1'];
function unique(arr) {
var res = arr.filter(function(item, index, array){
return array.indexOf(item) === index;
})
return res;
}
console.log(unique(arr2));
ES6
var arr = [1,3,1,4,1,5,6,3,1,2];
Array.from(new Set(arr));//[1, 3, 4, 5, 6, 2]
[... new Set(arr)];//[1, 3, 4, 5, 6, 2]
网友评论