Create a single value array in JavaScript

前端 未结 7 633
再見小時候
再見小時候 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: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]); 

提交回复
热议问题