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 }