Array, Set, Map, Object learning summary

Array and Set contrast

The container is a multi-value memory, the two can be interchangeable, but there are differences in the use of scenarios. as follows:
  • The method of Array indexOf method has a lower efficiency than the Set
  • Set does not contain a duplicate value (to be realized using this characteristic of an array weight)
  • Set delete a value by the delete method, and Array only through the splice. Ease of use of both the former better
  • Many new methods Array of map, filter, some, every, etc. Set is not (but can be used by both interchangeable)

Set set of operations ( WeakSet )

let set = new Set()
// Set转化为数组
let arr = Array.from(set)
let arr = [...set]
// 实例属性(继承自Set)
set.constructor === Set 
set.size 
// 操作方法
set.add(1) // 添加一个值
set.delete(1) //删除一个值
set.has(1) //判断是否有这个值(Array中的indexOf)
set.clear() //清除所有值
// 获取用于遍历的成员方法(Set的遍历顺序就是插入顺序)
set.keys() // 返回键名的遍历器
set.values() // 返回键值得遍历器
set.entries() // 返回键值对的遍历器
set.forEach() // 循环遍历每个值(和Array的方法一致)
for (let key of set.keys()){}
for (let val of set.values()){}
for (let entry of set.entries()){}
// 使用数组方法来处理set值
set = new Set(arr)
set = new Set([...set].map((x) => x = x * 2))
set = new Set([...set].filter((x) => x > 2))

Object Map and contrast

Object is a string - value, Map is value - value
  • Object key for the string type, Map of bonds of any type
  • Object size calculated manually, Map.size size may be obtained
  • Map sort order is inserted
  • Object has a prototype, so there is some default mapping of the key. It can be understood as Map = Object.create (null)

Map of the collection method

let map = new Map()
// 实例属性(继承自Map)
map.constructor === Map
map.size
// 操作方法
map.set(1,2)
map.get(1)
map.delete(1)
map.has(1)
map.clear()
// 遍历方法
map.keys()
map.values()
map.entries()
map.forEach()
// Map和数组的转换
map = new Map([['key','val'],[2,1]]) // 要求双成员数组
let arr = [...map]
// 值得注意的是Map的键是跟内存绑定的
map.set([1], 's')
map.get([1])
let arr = [1]
let arr1 = [1]
map.set(arr, 's')
map.get(arr)
map.set(arr1, 's')
map.get(arr1)

Reference Documents

Array
the Set and Map
the Set and Map Ruan Yifeng Tutorials

Guess you like

Origin www.cnblogs.com/jlfw/p/11966015.html