Create a single value array in JavaScript

前端 未结 7 630
再見小時候
再見小時候 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:44

    Here is my solution.

        var tech = new Array(); //create an empty array
        tech.push(21); //Append items to the array
        console.log(tech); // console array the array
    

    Be careful to avoid this; var array = new Array(n), this creates an empty array of length n, then if you push; you will simply append the new item to the end of the array and the new array length will be n+1 and your new array will look like this array = [Empty*21,new item ]

提交回复
热议问题