Create a single value array in JavaScript

前端 未结 7 629
再見小時候
再見小時候 2021-01-01 08:59

why is the following code showing undefined? Are we not allowed to create an array with a single value? Putting two values won\'t show this error. Is this a pro

7条回答
  •  执笔经年
    2021-01-01 09:31

    new Array(21) creates an array with a length of 21. If you want to create a single-value array, consisting of a number, use square brackets, [21]:

    var tech = [ 21 ];
    alert(tech[0]);
    

    If you want to dynamically fill an array, use the .push method:

    var filler = [];
    for(var i=0; i<5; i++){
        filler.push(i); //Example, pushing 5 integers in an array
    }
    //Filler is now equivalent to: [0, 1, 2, 3, 4]
    

    When the Array constructor receives one parameter p, which is a positive number, an array will be created, consisting of p elements. This feature is can be used to repeat strings, for example:

    var repeat = new Array(10);
    repeat = repeat.join("To repeat"); //Repeat the string 9x
    

提交回复
热议问题