javascript create empty array of a given size

前端 未结 8 1186
陌清茗
陌清茗 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:19

    We use Array.from({length: 500}) since 2017.

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

    Try using while loop, Array.prototype.push()

    var myArray = [], X = 3;
    while (myArray.length < X) {
      myArray.push("")
    }
    

    Alternatively, using Array.prototype.fill()

    var myArray = Array(3).fill("");
    
    0 讨论(0)
  • 2020-12-12 12:31

    If you want to create anonymous array with some values so you can use this syntax.

    var arr = new Array(50).fill().map((d,i)=>++i)
    console.log(arr)

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

    In 2018 and thenceforth we shall use [...Array(500)] to that end.

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

    As of ES5 (when this answer was given):

    If you want an empty array of undefined elements, you could simply do

    var whatever = new Array(5);
    

    this would give you

    [undefined, undefined, undefined, undefined, undefined]
    

    and then if you wanted it to be filled with empty strings, you could do

    whatever.fill('');
    

    which would give you

    ["", "", "", "", ""]
    

    And if you want to do it in one line:

    var whatever = Array(5).fill('');
    
    0 讨论(0)
  • 2020-12-12 12:43
    var arr = new Array(5);
    console.log(arr.length) // 5
    
    0 讨论(0)
提交回复
热议问题