⊗jsSpItSpr 73 of 294 menu

Spread operator and iterators in JavaScript

The spread operator expands any object that has an iterator. This will take the default iterator. Let's look at an example. Let we have the following Map collection:

let map = new Map(); map.set('a', 1); map.set('b', 2); map.set('c', 3);

By default, when decomposed, a two-dimensional array will be obtained:

let arr = [...map]; console.log(arr); // [['a', 1], ['b', 2], ['c', 3]]

To obtain an array of keys, we decompose the corresponding iterator:

let arr = [...map.keys()]; console.log(arr); // ['a', 'b', 'c']

Let's do the same to get an array of values:

let arr = [...map.values()]; console.log(arr); // [1, 2, 3]

Expand the next object with spread operator:

let obj = { a: 1, b: 2, c: 3, [Symbol.iterator]: function *(){ for (let key in this){ yield this[key]; } } };
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline