說到數組去重,其實大家都不陌生
傳統型數組去重的其中一種方法:
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去重只能去重基本數據類型。