Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1879
花落未央
花落未央 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:07

    I have nothing against:

    Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
    new Array(5+1).join('0').split('').map(parseFloat);
    

    suggested by Zertosh, but in a new ES6 array extensions allow you to do this natively with fill method. Now IE edge, Chrome and FF supports it, but check the compatibility table

    new Array(3).fill(0) will give you [0, 0, 0]. You can fill the array with any value like new Array(5).fill('abc') (even objects and other arrays).

    On top of that you can modify previous arrays with fill:

    arr = [1, 2, 3, 4, 5, 6]
    arr.fill(9, 3, 5)  # what to fill, start, end
    

    which gives you: [1, 2, 3, 9, 9, 6]

提交回复
热议问题