用js实现数组去重
实现数组去重,可以使用Set数据结构或者遍历原数组进行判断的方式。
- 使用Set数据结构
let arr = [1, 2, 3, 3, 4, 4, 5];
let newArr = [...new Set(arr)];
console.log(newArr); // [1, 2, 3, 4, 5]
- 遍历原数组进行判断
let arr = [1, 2, 3, 3, 4, 4, 5];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i]);
}
}
console.log(newArr); // [1, 2, 3, 4, 5]
其中,使用indexOf()方法判断新数组中是否已经存在当前元素,如果不存在则将其添加到新数组中。
原文地址: https://www.cveoy.top/t/topic/l5H 著作权归作者所有。请勿转载和采集!