传统方法
// 循环比对
function unique1(arr) {
const res = [];
arr.forEach((item) => {
if (res.indexOf(item) < 0) {
res.push(item);
}
});
return res;
}
使用Set
// ES6 的Set
function unique2(arr) {
const res = new Set(arr);
return [...res];
}
使用filter
//利用filter
function unique3(arr) {
return arr.filter(function (item, index, arr) {
//当前元素,在原始数组中的第一个索引==当前索引值,否则返回当前元素
return arr.indexOf(item, 0) === index;
});
}
版权声明:本文为qq_43706089原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。