ES6下的數組去重


說到數組去重,其實大家都不陌生

傳統型數組去重的其中一種方法:

Array.prototype.unique3 = function(){
 var res = [];
 var json = {};
 for(var i = 0; i < this.length; i++){
  if(!json[this[i]]){
   res.push(this[i]);
   json[this[i]] = 1;
  }
 }
 return res;

}

 

那么在ES6下也有一個數組去重的方法 Set:

 

var set = new Set();

console.log(set([1,2,3,3])) //[1,2,3] ;

但是有一點要注意的是。Set方法並不能把數組對象去重,例如:

var arr = {[a:"apple"],[a:"apple"],[a:"apple"],[b:"boy"]};

console.log(set(arr)) //{[a:"apple"],[a:"apple"],[a:"apple"],[b:"boy"]} ;

事實證明,ES6下的Set去重只能去重基本數據類型。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM