could someone explain to me how exactly map.entries() and destructuring work?
var numbers = new Map()
numbers.set(1,'one')
numbers.set(2,'two')
numbers.set(3,'three')
numbers.set(4,'four')
var [key,value] = numbers.entries() // returns key as [1,'one'] and value as [2,'two']
//but when using for..of loop
for(let [key,value] of numbers.entries()){
console.log(key,value)
} // it works and console logs keys and values
why does this work in a for..loop? and how does the .entries() method work exactly?i've been looking all over the web and couldn't really understand it.
The entries
method returns an iterator. Each value that the iterator yields is a key/value pair (array with 2 elements).
One way to get a grip on this, is to see what happens if you consume the iterator into a new array:
var numbers = new Map().set(1,'one').set(2,'two').set(3,'three').set(4,'four');
// Get everything from the iterator into a new array:
var arr = Array.from(numbers.entries());
console.log(arr);
Note that you get a series of key/value pairs into a new array:
[ [1, "one"], [2, "two"], [3, "three"], [4, "four"] ]
Now to your code. The first assignment to key
and value
is misleading, because you are not getting one key and one value. Instead you're grabbing the first two pairs that are yielded by the entries()
iterator.
If you really want to get the first key with the corresponding value in 2 variables, you need to write:
var [[key, value]] = numbers.entries();