js—去除重复的数

js—去除重复的数

方法一:

let arr =[1,2,2,2,3,4,5,5,6,6,7,8];
let newArr = []
outer :for (let i=0;i<arr.length;i++) {
    for (let j=0;j<newArr.length;j++) {
        if (arr[i]===newArr[j]) {
            continue outer;//终止名字为outer的循环
        }
    }
    newArr.push(arr[i])
}
console.log(newArr)

方法二,用indexof:

let arr =[1,2,2,2,3,4,5,5,6,6,7,8];
let a=[]
for(let i=0;i<arr.length;i++){
    if(a.indexOf(arr[i]) == -1){
        a.push(arr[i])
    }
}
console.log(a)

 用include去重:

let arr =[1,2,2,2,3,4,5,5,6,6,7,8,2];
let a=[]
for(let i=0;i<arr.length;i++){
    if(a.includes(arr[i])==false){
        a.push(arr[i])
    }
}
console.log(a)

用集合去重:

let arr =[1,2,2,2,3,4,5,5,6,6,7,8,2];
let s1=new Set(arr)
console.log(s1)
let arr2=[...s1]
console.log(arr2)

 

posted on 2019-07-02 17:20  GaoW  阅读(5031)  评论(0编辑  收藏  举报

导航