ES6下的數組去重

說到數組去重,其實你們都不陌生json

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

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;app

}this

 

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

 

var set = new Set();對象

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

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

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

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

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

相關文章
相關標籤/搜索