Most efficient way to create a zero filled JavaScript array?

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

    To create an all new Array

    new Array(arrayLength).fill(0);
    

    To add some values at the end of an existing Array

    [...existingArray, ...new Array(numberOfElementsToAdd).fill(0)]

    Example

    //**To create an all new Array**
    
    console.log(new Array(5).fill(0));
    
    //**To add some values at the end of an existing Array**
    
    let existingArray = [1,2,3]
    
    console.log([...existingArray, ...new Array(5).fill(0)]);

提交回复
热议问题