js中,数组去重的方法的总结(温故而知新)
1.假设状态变量,外层进行数组遍历,在数组遍历的内部在进行遍历通过,新数组和原数组的比对,进行取重操作
代码:
var oldArr = ['a', 'b', 121, 22, 88, 88, 22,22,1111,0,99]
var newArr = []
for (let i = 0; i < oldArr.length; i++) {
var bl = true
for (let j = 0; j < newArr.length; j++) {
if (oldArr[i] === newArr[j]) {
bl = false
break
}
}
if (bl) {
newArr.push(oldArr[i])
}
}
console.log(newArr) // ["a", "b", 121, 22, 88, 1111, 0, 99]
2.利用indexOf方法,来检索新数组中没有重复的值,没有返回-1,把没有重复的值推入新数组
代码:
var oldArr = ['a','a','b', 121, 22, 88, 88, 22,22,1111,0,99]
var newArr = []
for(let i=0;i<oldArr.length;i++){
if(newArr.indexOf(oldArr[i])===-1){
newArr.push(oldArr[i]);
}
}
console.log(newArr);//["a", "b", 121, 22, 88, 1111, 0, 99]
另一种是indexOf的延续,但是有一些区别
代码:
var oldArr = ['a','a','b', 121, 22, 88, 88, 22,22,1111,0,99]
var newArr = []
for(let i=0;i<oldArr.length;i++){
if(oldArr.indexOf(oldArr[i])===i){
newArr.push(oldArr[i]);
}
}
console.log(newArr);//["a", "b", 121, 22, 88, 1111, 0, 99] */
3.