javascript create empty array of a given size

前端 未结 8 1188
陌清茗
陌清茗 2020-12-12 12:11

in javascript how would I create an empty array of a given size

Psuedo code:

X = 3;
createarray(myarray, X, \"\");

output:

相关标签:
8条回答
  • 2020-12-12 12:45

    1) To create new array which, you cannot iterate over, you can use array constructor:

    Array(100) or new Array(100)


    2) You can create new array, which can be iterated over like below:

    a) All JavaScript versions

    • Array.apply: Array.apply(null, Array(100))

    b) From ES6 JavaScript version

    • Destructuring operator: [...Array(100)]
    • Array.prototype.fill Array(100).fill(undefined)
    • Array.from Array.from({ length: 100 })

    You can map over these arrays like below.

    • Array(4).fill(null).map((u, i) => i) [0, 1, 2, 3]

    • [...Array(4)].map((u, i) => i) [0, 1, 2, 3]

    • Array.apply(null, Array(4)).map((u, i) => i) [0, 1, 2, 3]

    • Array.from({ length: 4 }).map((u, i) => i) [0, 1, 2, 3]

    0 讨论(0)
  • 2020-12-12 12:45

    You can use both javascript methods repeat() and split() together.

    " ".repeat(10).split(" ")
    

    This code will create an array that has 10 item and each item is empty string.

    const items = " ".repeat(10).split(" ")
    
    document.getElementById("context").innerHTML = items.map((item, index) => index)
    
    console.log("items: ", items)
    <pre id="context">
    
    </pre>

    0 讨论(0)
提交回复
热议问题