//该方法要比indexOf性能好
const arr = [2,5,6,5,2,8,9];
const obj = {};
for (let i = 0; i < 100000; i++) {
arr.push(Math.round(Math.random()*10000));
}
console.time();
arr.forEach((item) =>{
obj[item] = 0;
});
// console.log(obj);//对象的键名不能重复,重复会被覆盖
const newArr = [];
for(const key in obj){
//对象的键名是字符串,用+转换成number类型
newArr.push(+key);
}
console.log(newArr);
console.timeEnd();
```
//indexOf去重
console.time();
const newArr1 = [];
arr.forEach((value) => {
if(newArr1.indexOf(value) === -1){
newArr1.push(value);
}
});
console.log(newArr1);
console.timeEnd();
测试结果效率比indexOf提高N多倍![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4e4b14bbd343b8156b7e14b6a194d368.png)