在 JavaScript 開發中,檢測陣列內是否有重複元素是常見需求。本文提供一個擴充 Array.prototype 的實用方法,能高效去除重複並回傳新陣列。
Array.prototype.del = function(){
var a = {}, c = [], l = this.length;
for (var i = 0; i < l; i++) {
var b = this[i];
// 使用「型別+值」作為鍵值,區分 1 與 "1" 等情況
var d = (typeof b) + b;
if (a[d] === undefined) {
c.push(b);
a[d] = 1;
}
}
return c;
}
var arr = [1, 2, "2", 3, 1, "hello", "hello", {a:1}, {a:1}];
var unique = arr.del();
// 結果: [1, 2, "2", 3, "hello", {a:1}, {a:1}]
// 注意:物件參考不同視為不重複
console.log(unique);
a 作為雜湊表,鍵值為 typeof 值 + 值,精準區分不同型別但數值相同的情況(如 1 vs "1")。c 並標記。此方法已掛載至 Array.prototype,可直接對任何陣列呼叫 .del() 取得去重後的新陣列,不修改原陣列。