Home > Web Front-end > JS Tutorial > body text

Detailed explanation of Map/WeakMap in ECMAScript6_javascript skills

WBOY
Release: 2016-05-16 15:55:24
Original
1149 people have browsed it

The JS object itself is a key-value structure. Why does ES6 need to add Map? What is the difference between it and ordinary JS objects?

1. Map

1. Map constructor

Let’s look at the simple usage of Map first

// 字符串作为key, 和JS对象类似
var map = new Map()
// set
map.set('name', 'John')
map.set('age', 29)
// get
map.get('name') // John
map.get('age') // 29
Copy after login

With this code, it seems that it is not as concise as JS objects

But the power of Map is that its key can be of any type

// 对象作为key演示
var xy = {x: 10, y: 20}  // 坐标
var wh = {w: 100, h: 200} // 宽高
var map = new Map()
// set
map.set(xy, '坐标')
map.set(wh, '宽高')
// get
map.get(xy) // '坐标'
map.get(wh) // '宽高'
Copy after login

The above demonstrates a Map using objects as keys. The following is an illustration

The Map constructor also supports passing arrays

var map = new Map([["name", "John"], ["age", "29"]])
 
// 遍历key
for (var key of map.keys()) {
  console.log(key) // name, age
}

Copy after login

2. Iteration

Use for of to iterate Map like Set, call map.keys() for keys, map.values() for values, and map.entries() for key-value entities

var map = new Map()
// set
map.set('name', 'John')
map.set('age', 29)
// get
map.get('name') // 'John'
map.get('age') // 29
 
// 遍历key
for (var key of map.keys()) {
  console.log(key)
}
 
// 遍历value
for (var val of map.values()) {
  console.log(val)
}
 
// 遍历实体
for (var arr of map.entries()) {
  console.log('key: ' + arr[0] + ', value: ' + arr[1])
}
 
// 遍历实体的简写
for (var [key, val] of map.entries()) {
  console.log('key: ' + key + ', value: ' + val)
}
 

Copy after login

3. Methods and properties

2. WeakMap

Differences from Map

Does not accept basic type values ​​as key names
No keys, values, entries and size
There are following methods

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!