javascript - Populate a map with a default value - Stack Overflow

I want to create a map of 48 default key value pairs.This code works fine:var m = new Map();for(var i=

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
Add a ment  | 

1 Answer 1

Reset to default 6

You 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

相关推荐

  • javascript - Populate a map with a default value - Stack Overflow

    I want to create a map of 48 default key value pairs.This code works fine:var m = new Map();for(var i=

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信