Javascript;storing values in array

javascript

I am trying to store values in array using javascript..but i get strange error in javascript.below is my code

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

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

alert(all[1]);
alert(all[2]);
alert(all[3]);

please check the code here : http://jsfiddle.net/D8Suq/

for all[1] and all[2] i am getting undefined error..but all[3] is working fine,,,am confused.some one please help me

Best 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]);