const arr = [1,2,2,3,4,4,4,4,5,5,6,7,8,8]
// 第一种方法 Array.from()
let setArr = new Set(arr) // 将数组转化成set结构 ==> Set { 1, 2, 3, 4, 5, 6, 7, 8 }
let r1 = Array.from(setArr) // 调用Array.from将set结构转化为数组
// 第二种方法 ...解构
let r2 = [...new Set(arr)]
// 附:for循环去重
let newArr = []
for(let i = 0; i < arr.length; i++){
if(newArr.indexOf(arr[i]) == -1){ // 只有当新数组里没有重复数据的时候才push
newArr.push(arr[i]) // 将旧数组遍历每一项添加到新数组里面
}
}
- indexOf()方法,该方法将从头到尾地检索数组,看它是否含有对应的元素。开始检索的位置在数组 start 处或数组的开头(没有指定 start 参数时)。如果找到一个 item,则返回 item 的第一次出现的位置。开始位置的索引为 0。如果在数组中没找到指定元素则返回 -1。