方法一:利用对象属性key排除重复项:遍历数组,每次判断对象中是否存在该属性,不存在就存储在新数组中。 方法二:var mySet = new Set(arr),Array.from(mySet)将 Set 转为数组返回.这个方法的优点是效率更高,代码简单,思路清晰,缺点是可能会有兼容性问题 方法三:filter+indexof 去重:
// 方式一:普通去重 // 数组的去重 Array.prototype.unique = function () { let arr = [] let len = this.length for (let i = 0; i < len; i++) { if (arr.indexOf(this[i]) == -1) arr.push(this[i]) } return arr } // let res = arr.unique() // console.log(res); // 方式二:里调用对象的hash方式储存 Array.prototype.unique2 = function () { let arr = [] let len = this.length let json = {} for (let i = 0; i < len; i++) { if (typeof json[this[i]] == "undefined") { arr.push(this[i]) json[this[i]] = true } } return arr } // 方式三:排序,之后找不相等的就行 Array.prototype.unique3 = function () { this.sort((a, b) => a - b) let len = this.length let arr = [] for (let i = 0; i < len; i++) { if (this[i] !== arr[arr.length - 1]) { arr.push(this[i]) } } return arr } // 方式四:利用Set Array.prototype.unique4 = function () { return [...new Set(arr)] } // 利用Map去重 Array.prototype.unique5 = function () { let map = new Map() let arr = [] let len = this.length for (let i = 0; i < len; i++) { console.log(map.has(this[i])); if (!map.has(this[i])) { map.set(this[i], this[i]) arr.push(this[i]) } } console.log(map); return arr }