Set 是一種集合的數據結構,Map是一種字典的數據結構
ES6的新語法,相似數組。區別惟一且無序的,沒有重複值
:成員是
Set自己是構造函數,用來生成Set的數據結構new Set([iterable])
javascript
const set = new Set(); [1,2,3,3,2,2].forEach(num => set.add(num)); console.log(set); // {1,2,3} // 去重 let arr = [1,2,3,3,4,3,2,2,1]; console.log([...new Set(arr)]); [1,2,3,4]
===
,主要區別是NaN能夠等於NaNSet的實例方法java
操做方法數組
轉換。 ```javascript let set = new Set([1,3,4,5]) let arr = Array.from(set) console.log(arr) //[1,3,4,5] // 或者經過解構賦值 let set = new Set([1,3,4,5]) let arr = [...set] console.log(arr) //[1,3,4,5] ``` - 遍歷方法(遍歷順序和插入順序一致) - keys() 返回包含全部鍵的迭代器 - values() 返回包含全部值的迭代器 - entries() 返回包含全部鍵值對的迭代器 - forEach(callback, thisArg) 對全部的成員進行callback操做,若是提供了thisArg回調中的this回事thisArg,無返回值 ```javascript let set = new Set([1,3,4,5,6,5,4,4]) console.log(set.keys()) // [Set Iterator] { 1, 3, 4, 5, 6 } console.log(set.values()) // [Set Iterator] { 1, 3, 4, 5, 6 } console.log(set.entries()) // [Set Entries] { [ 1, 1 ], [ 3, 3 ], [ 4, 4 ], [ 5, 5 ], [ 6, 6 ] } set.forEach((key, value) => { console.log(`=======${key}:${value}=======`) }) ``` - thisArg參數的用法,也能夠用箭頭函數,緣由是箭頭函數沒有自身的this,指向的是父級的this ```javascript // 傳入this值 function Counter() { this.sum = 0; this.count = 0; } Counter.prototype.add = function(array) { array.forEach(function(currentValue, index) { this.sum += currentValue; this.count++; }, this) } let obj = new Counter() obj.add([1,2,3,4,5]) console.log(obj.count, obj.sum) // 5 15 // 或者用箭頭函數 Counter.prototype.add = function(array) { array.forEach((currentValue, index) => { this.sum += currentValue; this.count++; }) } ```
字典和集合的區別
Map 和 Object 的區別
Map | Object | |
---|---|---|
意外的鍵 | 只能顯式的插入鍵 | 原型上可能會有其餘鍵 |
鍵的類型 | 能夠是任意類型,包括函數、對象等 | 只能是string或者Symbol |
鍵的順序 | 當迭代的時候,是按照插入的順序迭代 | 無序的 |
Size | 直接經過size屬性獲取 | 只能計算 |
迭代 | 直接迭代 | 經過方法獲取key值後迭代 |
性能 | 增刪改的表現更好 | 無優化 |
任何具備iterator接口,且每一個成員都是雙元素的數據的數據結構,均可以看成Map構造函數的參數。
let map = new Map([['w','d'],['s','v']]) console.log(map) // Map(2) { 'w' => 'd', 's' => 'v' }
Map的實例屬性數據結構
Map的實例方法函數
操做方法性能
遍歷方法(遍歷順序和插入順序一致)優化
let map = new Map([['w','d'],['s','v']]) map.forEach((value,key) => { console.log(`${key}=>${value}`) // w=>d // s=>v })
與其餘數據結構的相互轉換
Map => Arraythis
let map = new Map([[1,2],[3,4]]) let arr = [...map] console.log(arr) // [ [ 1, 2 ], [ 3, 4 ] ]
Array => Mapprototype
let arr = [[1,2],[3,4]] let map = new Map(arr) console.log(map) // Map(2) { 1 => 2, 3 => 4 }
Map => Objectcode
注意,由於Map的鍵能夠存任意類型,因此要將鍵轉爲字符串而後添加到obj中,不然存入的就是'[object,object]'
let map = new Map() map.set({a:1}, 1) map.set({b:2}, 2) function mapToObject(map){ let obj = {} for (let [key, value] of map) { obj[JSON.stringify(key)] = value } return obj } console.log(mapToObject(map)) //{ '{"a":1}': 1, '{"b":2}': 2 }
Object => Map
let obj = {a: 1,b: 2} function objToMap(obj){ let map = new Map() for (let key of Object.keys(obj)) { map.set(key, obj[key]) } return map } console.log(objToMap(obj)) // Map(2) { 'a' => 1, 'b' => 2 }