Criado por James Drummond
mais de 9 anos atrás
|
||
> let map = new Map(); > map.set('foo', 123); > map.get('foo') 123 > map.has('foo') true > map.delete('foo') true > map.has('foo') false
let map = new Map([ [ 1, 'one' ], [ 2, 'two' ], [ 3, 'three' ], // trailing comma is ignored ]);Also:let map = new Map() .set(1, 'one') .set(2, 'two') .set(3, 'three');
Any value can be a key, even an object: let map = new Map(); const KEY1 = {}; map.set(KEY1, 'hello'); console.log(map.get(KEY1)); // hello const KEY2 = {}; map.set(KEY2, 'world'); console.log(map.get(KEY2)); // world
Iterate using for and let:for (let value of map.values()) { console.log(value); } Destructuring enables you to access the keys and values directly: for (let [key, value] of map.entries()) { console.log(key, value); } Or you can just say: for (let [key, value] of map) { console.log(key, value); }
The Spread operator (...)The spread operator (...) turns an iterable into the arguments of a function or parameter call.> let arr = [2, 11, -1]; > Math.max(...arr) 11 Spread also turns an iterable into the elements of an array. That lets us convert the result of Map.prototype.keys() (an iterable) into an array: let map = new Map([ [1, 'one'], [2, 'two'], [3, 'three'], ]); let arr = [...map.keys()]; // [1, 2, 3]
Quer criar suas próprias Notas gratuitas com a GoConqr? Saiba mais.