let arr = [1, 1, 1, 2, 2, 3, 3, 4, 4]
// 传统封装去重函数
// function unique (arr) {
// let res = []
// arr.forEach((item) => {
// if (res.indexOf(item) < 0) {
// res.push(item)
// }
// })
// return res
// }
// const result = unique(arr) // 调用unique方法并赋值给result
// console.log(result, 'here')
// 使用set
function unique (arr) {
const res = new Set(arr)
return [...res]
}
const result = unique(arr)
console.log(result, 'here')
本文介绍了一种使用JavaScript中的Set对象进行数组元素去重的方法,相比于传统的遍历和indexOf检查,这种方法更加简洁高效。
3487

被折叠的 条评论
为什么被折叠?



