Map/weakmap detailed _javascript skills in ECMASCRIPT6

Source: Internet
Author: User

JS object itself is a key-value structure, ES6 why also need to add map, it and ordinary JS object What is the difference?

One, Map

1. Map Builder

First look at the simple use of map

string as key, and JS object similar to
var map = new map ()
//Set
map.set (' name ', ' John ') map.set (' Age ', ')
//Get
   map.get (' name ')//John
map.get (' age ')//29

So on the code, it does not look like the JS object is concise

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

Object as key demo
var xy = {x:10, y:20}  //coordinate
var wh = {w:100, h:200}//Width high
var map = new map ()
// Set
map.set (xy, ' coordinates ')
map.set (WH, ' width high ')
//Get
map.get (XY)//' coordinates '
map.get (WH)//' Width high '

The above shows a map with objects as key. The following is a diagram

The map constructor also supports array-passing methods

var map = new Map ([["Name", "John"], ["Age", "]"])
 
//Traversal key for
(Var key of Map.keys ()) {
  Console.log (key )//Name, age
}

2. Iteration

Iterate over the map with for of, as set, the key calls Map.keys (), the value calls Map.values (), and the key-value entity calls Map.entries ()

var map = new map ()
//Set
map.set (' name ', ' John ')
map.set (' age ', ')
//Get
map.get (' name ')//' John '
map.get (' age ')//I
 
//traversal key for
(Var key of Map.keys ()) {
  Console.log (key)
}
 
// Traversal value for (
var val of Map.values ()) {
  Console.log (val)
}
 
//Traversal entity for
(Var arr of map.entries ( ) {
  console.log (' key: ' + arr[0] + ', value: ' + arr[1])
}
 
///Iterate through the entity's shorthand for
(var [key, Val] of Map.entr IES ()) {
  Console.log (' key: ' + key + ', value: ' + Val ')
}
 

3. Methods and properties

Second, Weakmap

The difference from map

Values of the base type are not accepted as key names
No keys, values, entries, and size
There are the following methods

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.