js基础面试题--数组去重
js基础面试题--数组去重
- 传统方式,遍历元素,挨个比较,去重
- 使用Set
- 考虑计算效率
方式一:
// 传统方式 function unique(arr) { const res = [] arr.forEach(item => { if (res.indexOf(item) < 0) { res.push(item) } }) return res } const res = unique([30, 10, 20, 30, 40, 10]) console.log(res) //[30, 10, 20, 40]
方式二:
// 使用 Set (无序,不能重复) function unique(arr) { const set = new Set(arr) return [...set] } const res = unique([30, 10, 20, 30, 40, 10]) console.log(res) //[30, 10, 20, 40]
建议: 能使用Set就使用Set。 Set比较快,传统方式需要循环。兼容性和速度看需求。