Create a single value array in JavaScript

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

    You can create an Array with a value using Array.of

    let arr = Array.of(8)
    console.log(arr)

    0 讨论(0)
  • 2021-01-01 09:29

    by new Array(21) you're actually creating an array with 21 elements in it.

    If you want to create an array with single value '21', then it's:

    var tech = [21];
    alert(tech[0]);
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-01 09:34

    guys the answer was as simple as this:

    <script>
    var tech = new Array();
    tech.push(21);
    alert(tech[0]);
    </script>
    
    0 讨论(0)
  • 2021-01-01 09:39

    can use push or use brackets notation , passing single value is like initialize length

    var tech = new Array();
    tech.push(10);
    console.log(tech[0]); 


    var tech = new Array(5);
    console.log(tech.length);  // length = 5
    tech.push(10);  // will add as a 6th element i.e. a[5]
    console.log(tech.length);   // length = 6
    console.log(tech[0]);   // undefined 
    console.log(tech[5]);  // 10 


    or the easy way

    var tech = [10];
    console.log(tech[0]); 

    0 讨论(0)
  • 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 ]

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