最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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());
发布评论

评论列表(0)

  1. 暂无评论