Home > Article > Web Front-end > Detailed explanation of Map and introduction to commonly used APIs
The following editor will bring you an es6 series tutorial_Detailed explanation of Map and introduction to commonly used APIs. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look
The Map type in ECMAScript 6 is an ordered list that stores many key-value pairs. Key-value pairs support all data types. Keys 0 and '0' will be treated as two different keys, and no cast conversion will occur.
How to use Map?
let map = new Map();
Common methods:
set(key, value): Add a new key-value pair element
get(key): Get the value corresponding to the key. If the value does not exist, return undefined
let map = new Map(); map.set( '0', 'ghostwu' ); map.set( 0, 'ghostwu' ); console.log( map.get( '0' ) ); //ghostwu console.log( map.get( 'name' ) ); //undefined;
let map = new Map(); var key1 = {}, key2 = {}; map.set( key1, 'ghostwu' ); map.set( key2, 22 ); console.log( map.get( key1 ) ); //ghostwu console.log( map.get( key2 ) ); //22
Okay Use the object as the key of the Map. Although there are two empty objects, strong type conversion will not occur.
has( key): Determine whether the key name exists
delete( key): Delete key names and corresponding values
clear(): Remove all key-value pairs in the map collection
size: The number of elements in the map collection
let map = new Map(); map.set( 'name', 'ghostwu' ); map.set( 'age', 22 ); console.log( map.has( 'name' ) );//true console.log( map.size ); //2 map.delete( 'name' ); console.log( map.has( 'name' ) );//false console.log( map.size ); //1 console.log( map.has( 'age' ) ); //true map.clear(); console.log( map.size ); //0 console.log( map.has( 'age' ) ); //false
Map supports array initialization, using a two-dimensional array, each array uses key-value pairs
let map = new Map( [ [ 'name', 'ghostwu' ], [ 'age', 22 ] ] ); console.log( map.has( 'name') ); //true console.log( map.has( 'age') ); //true console.log( map.size ); //2 map.set( 'sex', 'man' ); console.log( map.size ); console.log( map.get( 'name' ) ); //ghostwu map.clear(); console.log( map.size ); //0
Map also supports the forEach method, support 2 parameters, the first one: function, the function supports 3 parameters (value, key, current map), the second one: this
let map = new Map( [ [ 'name', 'ghostwu' ], [ 'age', 22 ] ] ); map.set( 'sex', 'man' ); map.forEach( function( val, key, cur ){ console.log( val, key, cur, this ); }, 100 );
The above is the detailed content of Detailed explanation of Map and introduction to commonly used APIs. For more information, please follow other related articles on the PHP Chinese website!