利用对象的属性不会重复这一特性,首先创建一个空对象,然后用 for 循环遍历,来校验数组元素是否重复。举例如下:
let a = [0,1,1,2,3,4,4,4];
let result = [];
let obj = {};
for(let i of a){
if (!obj[i]){
result.push(i);
obj[i] = 1;
}
}
console.log(result);
console.log(obj);
输出结果:
[0, 1, 2, 3, 4]
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1}
另外,也可以用ES6的Set结构来去重,使用起来也很方便。
网友评论