Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1241
花落未央
花落未央 2020-11-22 05:58

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

30条回答
  •  被撕碎了的回忆
    2020-11-22 06:11

    If you use ES6, you can use Array.from() like this:

    Array.from({ length: 3 }, () => 0);
    //[0, 0, 0]
    

    Has the same result as

    Array.from({ length: 3 }).map(() => 0)
    //[0, 0, 0]
    

    Because

    Array.from({ length: 3 })
    //[undefined, undefined, undefined]
    

提交回复
热议问题