Fill in the card with default value

I want to create a map with 48 default key pairs. This code works fine:

var m = new Map();

for(var i=1; i <= 48 ; i++) {
  m.set(i,'0')
}

But, I want to know if this can be done without using for a loop.

+4
source share
1 answer

You can pass an array to the constructor Map:

const map = new Map([...Array(48)].map((_, i) => [i + 1, '0']));

If your first key might be 0instead 1, this would be a cleaner solution:

const map = new Map(Array(48).fill('0').entries());
+6
source

Source: https://habr.com/ru/post/1684686/


All Articles