Array.prototype.uniq = function () { return [...new Set(this)] }
Array.prototype.uniq = function () { // 1.使用set的特点进行去重,如果this指向比较复杂可以在外面定义一个that接受this return Array.from(new Set(this)) // 2.使用循环,定义一个数组接受未存在的值,重复的值不会存进去 let newArr = [] this.forEach(item=>{ if(!newArr.includes(item)) newArr.push(item) }) return newArr }
Array.prototype.uniq = function () { let hasNaN = false; for(let i = this.length - 1; i >= 0; i--){ if(this[i] != this[i]){ if(!hasNaN) { hasNaN = true; } else { this.splice(i, 1); } } else if(this.indexOf(this[i]) !== i) { this.splice(i, 1); } } return this; } // [true, false, null, undefined, 0, 1, {…}, {…}, 'a', NaN]这个NaN的位置还可能在最后,这个校验没有覆盖住
Array.prototype.uniq = function () { let res = []; flag = 0; this.forEach(item => { console.log(item); if(item != item) { if(flag < 1) res.push(item); flag ++; } if(res.indexOf(item) == -1 && item == item) res.push(item); }) return res; }
Array.prototype.uniq = function () { return [...new Set(this)]; }