es6數組去重的方法其實是有三種的,即利用Set對象和數組的from方法,具體的代碼語法為“Array.from(newSet(arr))”;利用Set與擴展運算符的方法,具體的代碼語法為“[...newSet(arr)]”;利用Map對象與數組的filter方法。
參考範例:
1、利用Set對象和數組的from方法,具體的代碼語法為“Array.from(newSet(arr))”。
示例代碼:
constnewArr=Array.from(newSet(arr));
代碼使用範例:
vararr=[1,1,8,8,12,12,15,15,16,16];
functionunique(arr){
returnArray.from(newSet(arr))
}
console.log(unique(arr))
//[1,8,12,15,16]
2、利用Set與擴展運算符,具體的代碼語法為“[...newSet(arr)]”。
示例代碼:
constnewArr=[...newSet(arr)];
3、利用Map對象與數組的filter方法。
代碼使用範例:
functionunique(arr){
constres=newMap();
returnarr.filter((a)=!res.has(a)res.set(a,1))
}
以上就是小編的分享了,希望能夠幫助到大家。