javascript

Why aren't my items being stored in my array?


I am trying to store values in array using JavaScript, but I get strange error:

let a = 1;
for (i = 0; i < 4; i++) {

  var all = new Array();
  all[i] = a;
  a++;
}

console.log(all[1]);
console.log(all[2]);
console.log(all[3]);

For all[1] and all[2] I am getting undefined error, but all[3] is working fine.


Solution

  • You are reassigning your array in every loop iteration (which deletes everything in it) instead of only before the whole loop.

    This should work as expected:

    var a = 1;
    var all = new Array();
    for(i=0;i<4;i++)
    {
        all[i]=a;
        a++;
    }
    
    alert(all[1]);
    alert(all[2]);
    alert(all[3]);