ES6 提供了新的數據結構 Set。它相似於數組,可是成員的值都是惟一的,沒有重複的值。數組
用法:new Set([iterable])數據結構
const set = new Set([1, 2, 3, 4, 4, 4]); //[1, 2, 3, 4]
Set結構有如下屬性:函數
Set結構有如下方法:prototype
const set = new Set(); //添加元素 set.add(1).add(2).add(2); set.size; //2 //檢查元素 set.has(2); //true set.has(3); //false //刪除元素 set.delete(2); set.has(2); //false //清空集合 set.clear(); set.size; //0
一些常見應用code
//數組去重 let arr = [1, 2, 3, 2, 5, 5]; let unique = [...new Set(arr)]; // [1, 2, 3, 5] //交,並,差集 let a = new Set([1, 2, 3]); let b = new Set([4, 3, 2]); // 並集 let union = new Set([...a, ...b]); // Set {1, 2, 3, 4} // 交集 let intersect = new Set([...a].filter(x => b.has(x))); // set {2, 3} // 差集 let difference = new Set([...a].filter(x => !b.has(x))); // Set {1}
JavaScript 的對象(Object),本質上是鍵值對的集合(Hash 結構),可是傳統上只能用字符串看成鍵。ES6中的Map結構也是鍵值對的集合,可是「鍵」的範圍不限於字符串,各類類型的值(包括對象)均可以看成鍵。對象
用法:new Map([iterable])ip
const map = new Map();
屬性和方法字符串
const map = new Map(); //添加鍵值對 map.set(1, 'aaa'); map.set(2, 'bbb').set('string', 'sssss'); map.get(1); // 'aaa' map.size; // 3 //刪除鍵值 map.delete(2); map.has(2); //false //遍歷方法 for(let key of map.keys()){ console.log(key); } // 1 // 'string' for(let key of map.values()){ console.log(key); } // 'aaa' // 'sssss' map.forEach(function(value, key, map){ console.log('key:'+key+', value:'+value) }) // 'key:1, value:aaa' // 'key:string, value:sssss'