脚本宝典收集整理的这篇文章主要介绍了JS去重的几种实现方法,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
方法1:ES6
新特性Set
Array.PRototyPE.rmSome = function() {
return Array.From(new Set(this));
}
方法2:利用对象名唯一
Array.prototype.rmSome = function() {
let tempObj = {}
this.foreach(item => {
if (tempObj[item]) {
return
} else {
tempObj[item] = item;
}
})
return Object.values(tempObj)
}
方法3:利用数组包含 [].includes [].indexOf
Array.prototype.rmSome = function () {
let tempArr = [];
this.forEach((item, index) => {
if (tempArr.includes(item)) {
return
} else {
tempArr.push(item)
}
})
return tempArr
}
方法4: 排序比较兄弟元素
Array.prototype.rmSome = function () {
const tempArr = this.sort();
tempArr.forEach((item, index) => {
for (let i = 0; i < tempArr.length; i++) {
if (tempArr[i] == tempArr[i + 1]) {
tempArr.splice(i, 1);
i--;
}
}
})
return tempArr
}
方法5: 双循环比较
Array.prototype.rmSome = function () {
for (let i = 0; i < this.length; i++) {
const node = this[i];
for (let j = i + 1; j < this.length; j++) {
if (node === this[j]) {
this.splice(j, 1);
j--;
}
}
}
return this
}
以上是脚本宝典为你收集整理的JS去重的几种实现方法全部内容,希望文章能够帮你解决JS去重的几种实现方法所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。