I want to create a map of 48 default key value 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 loop.
I want to create a map of 48 default key value 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 loop.
Share Improve this question asked Aug 29, 2017 at 17:25 prisoner_of_azkabanprisoner_of_azkaban 7682 gold badges9 silver badges28 bronze badges 4- What's wrong with a for loop? – Jeremy Thille Commented Aug 29, 2017 at 17:28
- nothing just wanted to know whether this can be done without for loop or not. – prisoner_of_azkaban Commented Aug 29, 2017 at 17:29
- Using a for loop is the best way to achieve what you need – koolkat Commented Aug 29, 2017 at 17:30
- As far as I know almost all solutions will use some kind of inner loop. – Manos Kounelakis Commented Aug 29, 2017 at 20:08
1 Answer
Reset to default 6You can pass an array to the Map
constructor:
const map = new Map([...Array(48)].map((_, i) => [i + 1, '0']));
If your first key can be 0
instead of 1
, this would be a cleaner solution:
const map = new Map(Array(48).fill('0').entries());
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745139689a4613371.html
评论列表(0条)