對於 JavaScript 數組去除重復項,現在有多種方法,其中一種是hash,如下:
if (!Array.prototype.unique) { Array.prototype.unique = function () { var hash = {}, result = [], item; for (var i = 0; i < this.length; i++) { item = this[i]; if ( !hash[item] ) { hash[item] = true; result.push(item); } } return result; }; }
但是該方法並不嚴謹,無法區分數字 1 和 字符串 '1'
var arr = [0, 1, '1', true, 5, true, false, undefined, undefined, null, null]; arr.unique();
修改一下,加上數據類型判斷:
if (!Array.prototype.unique) { Array.prototype.unique = function () { var hash = {}, result = [], type = '', item; for (var i = 0; i < this.length; i++) { item = this[i]; type = Object.prototype.toString.call(item); if ( !hash[item + type] ) { hash[item + type] = true; result.push(item); } } return result; }; }
至少現在對5種原始數據類型的值可以准確去重了,對某些引用類型的值──數組,函數,也可以,但是對象類型──{"name": 1}, {"name": 2}就沒法區分了。