js数组去重
Sonder
2020-04-14
771字
2分钟
浏览 (2.6k)
第一种:通过ES6新特性Set()
例如: var arr = [1, 2, 3, 1, 2]; var newArr= [...new Set(arr)]
![image.png](https://i.loli.net/2020/04/14/L6RecIOgVJnbt9s.png)
第二种:封装函数利用
function uniqueEasy(arr) {
if(!arr instanceof Array) {
throw Error('当前传入的不是数组')
}
let list = []
let obj = {}
arr.forEach(item => {
if(!obj[item]) {
list.push(item)
obj[item] = true
}
})
return list
}
![image.png](https://i.loli.net/2020/04/14/HX6AgGU4oWdCJDx.png)
第三种:indexOf 判断
var arr=['12','32','89','12','12','78','12','32'];
function u_arr(array) {
var h = [];
for (var i = 0;i<array.length; i++) {
if(h.indexOf(array[i]) == -1) {
h.push(array[i])
}
}
return h;
}
var sarr=u_arr(arr);
console.log(sarr)
Array.from
console.log(Array.from(new Set([2, 3, 3, 5, 6]))); //[2,3,5,6]