题目描述
为 Array 对象添加一个去除重复项的方法
输入
[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
输出
[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']
解决
- Array.prototype.uniq = function () {
- let res = []
- let hasNaN = false
- this.forEach(e => { // 循环数组
- if(res.indexOf(e) === -1) { // res 中没有就添加
- if(e !== e) { // 判断是否为 NAN, 因为精度的原因, NaN === NaN 返回 false
- if(!hasNaN) {
- res.push(e)
- hasNaN = true
- }
- } else {
- res.push(e)
- }
- }
- })
- return res
- }
来源: http://www.bubuko.com/infodetail-3670900.html