//[false,true,undefined,null,NaN,0,0,1,1,{},{},'a','a',NaN] 为Array对象添加一个去重方法(仅限 Map和Set)
//[false, true, undefined, null, NaN, 0, 1, {…}, {…}, "a"]
let arr = [false,true,undefined,null,NaN,0,0,1,1,{},{},'a','a',NaN]
Array.prototype.unique1 = function () {
if(!Array.isArray(this)) return false
return [...new Set(this)]
}
console.log(arr.unique1());
Array.prototype.unique2 = function () {
if(!Array.isArray(this)) return false
let newArr = []
let temMap = new Map()
for(let i=0;i<this.length;i++) {
if(!temMap.has(this[i])) {
temMap.set(this[i],1)
newArr.push(this[i])
}
}
return newArr
}
console.log(arr.unique2());
数组去重(map和set)
最新推荐文章于 2024-05-15 11:11:43 发布