In questo tutorial imparerai a conoscere le mappe JavaScript e le mappe deboli con l'aiuto di esempi.
JavaScript ES6 ha introdotto due nuove strutture dati, ovvero Map
e WeakMap
.
La mappa è simile agli oggetti in JavaScript che ci consente di memorizzare elementi in una coppia chiave / valore .
Gli elementi in una mappa vengono inseriti in un ordine di inserimento. Tuttavia, a differenza di un oggetto, una mappa può contenere oggetti, funzioni e altri tipi di dati come chiave.
Crea mappa JavaScript
Per creare un Map
, usiamo il new Map()
costruttore. Per esempio,
// create a Map const map1 = new Map(); // an empty map console.log(map1); // Map ()
Inserisci elemento nella mappa
Dopo aver creato una mappa, puoi utilizzare il set()
metodo per inserirvi elementi. Per esempio,
// create a set let map1 = new Map(); // insert key-value pair map1.set('info', (name: 'Jack', age: 26)); console.log(map1); // Map ("info" => (name: "Jack", age: 26))
È inoltre possibile utilizzare oggetti o funzioni come tasti. Per esempio,
// Map with object key let map2 = new Map(); let obj = (); map2.set(obj, (name: 'Jack', age: "26")); console.log(map2); // Map (() => (name: "Jack", age: "26"))
Accesso agli elementi della mappa
È possibile accedere agli Map
elementi utilizzando il get()
metodo. Per esempio,
let map1 = new Map(); map1.set('info', (name: 'Jack', age: "26")); // access the elements of a Map console.log(map1.get('info')); // (name: "Jack", age: "26")
Controlla gli elementi della mappa
È possibile utilizzare il has()
metodo per verificare se l'elemento è in una mappa. Per esempio,
const set1 = new Set((1, 2, 3)); let map1 = new Map(); map1.set('info', (name: 'Jack', age: "26")); // check if an element is in Set console.log(map1.has('info')); // true
Rimozione di elementi
È possibile utilizzare clear()
e il delete()
metodo per rimuovere elementi da una mappa.
Il delete()
metodo restituisce true
se esiste una coppia chiave / valore specificata ed è stata rimossa oppure restituisce false
. Per esempio,
let map1 = new Map(); map1.set('info', (name: 'Jack', age: "26")); // removing a particular element map1.delete('address'); // false console.log(map1); // Map ("info" => (name: "Jack", age: "26")) map1.delete('info'); // true console.log(map1); // Map ()
Il clear()
metodo rimuove tutte le coppie chiave / valore da un oggetto Map. Per esempio,
let map1 = new Map(); map1.set('info', (name: 'Jack', age: "26")); // removing all element map1.clear(); // false console.log(map1); // Map ()
Dimensione mappa JavaScript
È possibile ottenere il numero di elementi in una mappa utilizzando la size
proprietà. Per esempio,
let map1 = new Map(); map1.set('info', (name: 'Jack', age: "26")); console.log(map1.size); // 1
Iterazione su una mappa
È possibile scorrere gli elementi della mappa utilizzando il ciclo for… of o il metodo forEach (). Si accede agli elementi nell'ordine di inserimento. Per esempio,
let map1 = new Map(); map1.set('name', 'Jack'); map1.set('age', '27'); // looping through Map for (let (key, value) of map1) ( console.log(key + '- ' + value); )
Produzione
nome- Jack età- 27 anni
Puoi anche ottenere gli stessi risultati del programma sopra usando il forEach()
metodo. Per esempio,
// using forEach method() let map1 = new Map(); map1.set('name', 'Jack'); map1.set('age', '27'); // looping through Map map1.forEach(function(value, key) ( console.log(key + '- ' + value) ))
Iterazione sui tasti mappa
Puoi iterare sulla mappa e ottenere la chiave usando il keys()
metodo. Per esempio,
let map1 = new Map(); map1.set('name', 'Jack'); map1.set('age', '27'); // looping through the Map for (let key of map1.keys()) ( console.log(key) )
Produzione
nome età
Iterazione sui valori della mappa
È possibile iterare sulla mappa e ottenere i valori utilizzando il values()
metodo. Per esempio,
let map1 = new Map(); map1.set('name', 'Jack'); map1.set('age', '27'); // looping through the Map for (let values of map1.values()) ( console.log(values); )
Produzione
Jack 27
Ottieni chiave / valori della mappa
È possibile iterare sulla mappa e ottenere la chiave / valore di una mappa utilizzando il entries()
metodo. Per esempio,
let map1 = new Map(); map1.set('name', 'Jack'); map1.set('age', '27'); // looping through the Map for (let elem of map1.entries()) ( console.log(`$(elem(0)): $(elem(1))`); )
Produzione
nome: Jack età: 27
Mappa JavaScript vs oggetto
Carta geografica | Oggetto |
---|---|
Maps can contain objects and other data types as keys. | Objects can only contain strings and symbols as keys. |
Maps can be directly iterated and their value can be accessed. | Objects can be iterated by accessing its keys. |
The number of elements of a Map can be determined by size property. | The number of elements of an object needs to be determined manually. |
Map performs better for programs that require the addition or removal of elements frequently. | Object does not perform well if the program requires the addition or removal of elements frequently. |
JavaScript WeakMap
The WeakMap is similar to a Map. However, WeakMap can only contain objects as keys. For example,
const weakMap = new WeakMap(); console.log(weakMap); // WeakMap () let obj = (); // adding object (element) to WeakMap weakMap.set(obj, 'hello'); console.log(weakMap); // WeakMap (() => "hello")
When you try to add other data types besides objects, WeakMap throws an error. For example,
const weakMap = new WeakMap(); // adding string as a key to WeakMap weakMap.set('obj', 'hello');
// throws error // TypeError: Attempted to set a non-object key in a WeakMap
WeakMap Methods
WeakMaps hanno metodi get()
, set()
, delete()
, e has()
. Per esempio,
const weakMap = new WeakMap(); console.log(weakMap); // WeakMap () let obj = (); // adding object (element) to WeakMap weakMap.set(obj, 'hello'); console.log(weakMap); // WeakMap (() => "hello") // get the element of a WeakMap console.log(weakMap.get(obj)); // hello // check if an element is present in WeakMap console.log(weakMap.has(obj)); // true // delete the element of WeakMap console.log(weakMap.delete(obj)); // true console.log(weakMap); // WeakMap ()
Le mappe deboli non sono iterabili
A differenza di Maps, WeakMaps non è iterabile. Per esempio,
const weakMap = new WeakMap(); console.log(weakMap); // WeakMap () let obj = (); // adding object (element) to WeakMap weakMap.set(obj, 'hello'); // looping through WeakMap for (let i of weakMap) ( console.log(i); // TypeError )
JavaScript Map
e WeakMap
sono stati introdotti in ES6 . Alcuni browser potrebbero non supportarne l'utilizzo. Per saperne di più, visita il supporto JavaScript Map e il supporto JavaScript WeakMap.