Most efficient way to create a zero filled JavaScript array?

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

    Elegant way to fill an array with precomputed values

    Here is another way to do it using ES6 that nobody has mentioned so far:

    > Array.from(Array(3), () => 0)
    < [0, 0, 0]
    

    It works by passing a map function as the second parameter of Array.from.

    In the example above, the first parameter allocates an array of 3 positions filled with the value undefined and then the lambda function maps each one of them to the value 0.

    Although Array(len).fill(0) is shorter, it doesn't work if you need to fill the array by doing some computation first (I know the question didn't ask for it, but a lot of people end up here looking for this).

    For instance, if you need an array with 10 random numbers:

    > Array.from(Array(10), () => Math.floor(10 * Math.random()))
    < [3, 6, 8, 1, 9, 3, 0, 6, 7, 1]
    

    It's more concise (and elegant) than the equivalent:

    const numbers = Array(10);
    for (let i = 0; i < numbers.length; i++) {
        numbers[i] = Math.round(10 * Math.random());
    }
    

    This method can also be used to generate sequences of numbers by taking advantage of the index parameter provided in the callback:

    > Array.from(Array(10), (d, i) => i)
    < [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Bonus answer: fill an array using String repeat()

    Since this answer is getting a good deal of attention, I also wanted to show this cool trick. Although not as useful as my main answer, will introduce the still not very known, but very useful String repeat() method. Here's the trick:

    > "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
    < [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]
    

    Cool, huh? repeat() is a very useful method to create a string that is the repetition of the original string a certain number of times. After that, split() creates an array for us, which is then map()ped to the values we want. Breaking it down in steps:

    > "?".repeat(10)
    < "??????????"
    
    > "?".repeat(10).split("")
    < ["?", "?", "?", "?", "?", "?", "?", "?", "?", "?"]
    
    > "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
    < [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]
    

提交回复
热议问题