要領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
}