- 去重的三种不同方法,原理相同,可以直接改变原数组,也可以创建新数组进行操作
一、indexOf查询
let newarr = []
const arr = [1, 23, 2, 3, 4, 4, 5, 4, 6]
for (let index = 0; index < arr.length; index++) {
if ((newarr.indexOf(arr[index])) === -1) {
newarr.push(arr[index])
}
}
console.log(newarr)
二、数组some方法
arr.forEach(value=>{
const ishas =newarr.some(v=>v===value)
if(ishas){
}else{
newarr.push(value)
}
})
三、双重for循环
for (let index = 0; index < arr.length; index++) {
for (let j = index+1; j < arr.length; j++) {
if(arr[index]===arr[j]){
arr.splice(j,1)
}
}
}