原文:https://github.com/mqyqingfeng/Blog/issues/27
indexOf 去重
var array = [1, 1, '1'];
function unique(array) {
var res = [];
for (var i = 0, len = array.length; i < len; i++) {
var current = array[i];
if (res.indexOf(current) === -1) {
res.push(current)
}
}
return res;
}
console.log(unique(array));
使用filter中的indexOf
var array = [1, 2, 1, 1, '1'];
function unique(array) {
var res = array.filter(function(item, index, array){
return array.indexOf(item) === index;
})
return res;
}
console.log(unique(array));
var array = [1, 2, 1, 1, '1'];
function unique(array) {
return Array.from(new Set(array));
}
==》
function unique(array) {
return [...new Set(array)];
}
网友评论