Set是無重複值的有序列表。Set會自動移除重複的值,所以你可使用它來過濾數組中重複的值並返回結果。es6
Map是有序的鍵值對,其中的鍵容許是任何類型。數組
Set和Map是es6新增的兩個數據集合。函數
es6新增了set類型,這是一種無重複值的有序列表。Set容許對它包含的數據進行快速訪問。測試
Set經過new Set()來建立,調用add()方法就能夠向Set中添加項目。檢查size屬性還能查看其中包含多少項。code
let set = new Set(); set.add(5); set.add("5"); console.log(set.size);//2
Set不會使用強制類型轉換來判斷值是否重複。還能夠向Set添加多個對象,他們不會被合併爲同一項。對象
let set = new Set(); let key1 = {}; let key2 = {}; set.add(key1); set.add(key2); console.log(set.size);//2
若是add()方法用相同的值進行了屢次調用,那麼在第一次以後的調用實際上會被忽略。get
let set = new Set(); set.add(5); set.add("5"); set.add(5);//被忽略 console.log(set.size);//2
你可使用數組來初始化一個Set,而且Set構造器確保不會重複使用這些值。回調函數
let set = new Set([1,2,3,4,5,2,6,5,5,5]); console.log(set.size);//6
雖然數值5在數組中出現了四次,可是Set中只有一個5io
你可使用has()方法來測試某個值是否存在於set中console
let set = new Set(); let key1 = {}; let key2 = {}; let key3 = {}; set.add(key1); set.add(key2); console.log(set.has(key1));//true console.log(set.has(key3));//false
使用delete()方法來移除單個值或者調用clear()方法將全部值從Set中移除。
let set = new Set([1, 2, 3, 4, 5, 2, 6, 5, 5, "5"]); console.log(set); set.delete(5); console.log(set.has(5));//false set.clear(); console.log(set.size);//0
forEach()方法還會被傳遞一個回調函數,該回調函數接收三個參數:
因爲Set沒有鍵,爲了使forEach方法與數組和map的forEach方法一致:將Set中的每一項同時認定爲鍵與值。
let set = new Set([1, 2]); set.forEach(function(value, key, ownerSet) { console.log(`${key} ${value}`) console.log(ownerSet === set); })
let arr = [1,2,4,3,2,5,5]; let set = new Set(arr); let arr1 = [...set]; console.log(arr1);
ES6的Map類型是鍵值對的有序列表,而鍵和值均可以是任意類型。鍵的比較使用的是Object.is(),所以你能夠將5與「5」同時做爲鍵,由於他們類型不一樣。
能夠調用set方法並傳遞一個鍵與一個關聯的值,來給Map添加項;此後使用鍵名來調用get()方法便能提取對應的值。
let map = new Map(); map.set("name", "cc"); map.set("age", 23); console.log(map.get("name"));//cc console.log(map.get("age"));//23
也可使用對象做爲鍵
let map = new Map(); let key1 = {}; let key2 = {}; map.set(key1, 5); map.set(key2, 8); console.log(map.get(key1));//5 console.log(map.get(key2));//8
你能將數組傳遞給Map構造器,以便使用數據來初始化一個Map。該數組中的每一項也必須是數組,內部數組的首個項會做爲鍵,第二項則爲對應值。所以整個Map就被這些雙項數組填充。
let map = new Map([ ["name", "cc"], ["age", 26] ]); console.log(map.has("name"));//true console.log(map.get("name"));//cc console.log(map.has("age"));//true console.log(map.get("age"));//26 console.log(map.size);//2
let map = new Map([ ["name", "cc"], ["age", 26] ]); map.forEach(function(value, key, source) { console.log(`${key}的值是${value}`); console.log(source === map); })