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:
javascriptlet 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:
javascriptlet arr = [...map];
console.log(arr); // [['a', 1], ['b', 2], ['c', 3]]
To obtain an array of keys, we decompose the corresponding iterator:
javascriptlet arr = [...map.keys()];
console.log(arr); // ['a', 'b', 'c']
Let's do the same to get an array of values:
javascriptlet arr = [...map.values()];
console.log(arr); // [1, 2, 3]
Задание 1
Expand the next object with spread operator:
javascriptlet obj = {
a: 1,
b: 2,
c: 3,
[Symbol.iterator]: function *(){
for (let key in this){
yield this[key];
}
}
};