1,利用Set()方法
let list = [1,2,1,2,4,4,5]
let Newlist = Array.from(new Set(list))
console.log(Newlist)//输出[ 1, 2, 4, 5 ]
2,新建一个数组,逐一保存原数组中的值,判断新数组中是否已有该数值,无则保存,有则不做操作,这样就可以返回一个无重复的数组
(1)用一个自建的函数判断新数组中是否已有该数值
let list = [1,2,1,2,4,4,5]
//新数组
let newList = new Array()//本方法用来传入数值num,查找数组arr中是否存在num,没有则返回false
function find(num, arr) {for (let i=0; i < arr.length; i++) {if (num == arr[i]) {return true}}return false
}
//逐个判断存入新数组
for(let i=0; i < list.length; i++) {if (!find(list[i], newList)) {newList.push(list[i])}
}
console.log(newList)//输出[ 1, 2, 4, 5 ]
(2)本方法也可以用indexOf方法来判断新数组中是否已有该数值
(indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置,如果没有找到匹配的字符串则返回 -1。)
let list = [1,2,1,2,4,4,5]
let newList = new Array()for(let i=0; i < list.length; i++) {if (newList.indexOf(list[i]) == -1) {newList.push(list[i])}
}
console.log(newList)//输出[ 1, 2, 4, 5 ]
(3)利用对象的属性来判断新数组中是否已有该数值
如果对象没有该值,返回一个false
let list = [1,2,1,2,4,4,5]
// list.sort()
let newList = new Array()
let obj = {}
for(let i=0; i < list.length; i++) {if(!obj[list[i]]) {newList.push(list[i])obj[list[i]] = true}
}console.log(newList)//输出[ 1, 2, 4, 5 ]
3.先排序,然后删除往后的相同项,利用到数组的splice方法

let list = [1,2,1,2,4,4,5]
list.sort()
for(let i=0; i < list.length; i++) {if(list[i] == list[i+1]) {list.splice(i,1)}
}console.log(list)//输出[ 1, 2, 4, 5 ]
4.利用双重for循环,删除重复的项
let list = [1,2,1,2,4,4,5]for (let i=0; i < list.length; i++) {for (let j=i + 1; j < list.length; j++) {if (list[i] == list[j]) {list.splice(j, 1)j--//由于删除后数组下一位补上,所以需要减一}}
}console.log(list)//输出[ 1, 2, 4, 5 ]



















