對于 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}就沒法區分了。
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!
新聞熱點
疑難解答