简体   繁体   中英

javascript;storing values in array

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

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

You are re-initializing the array inside of the for-loop, overwriting any data you had previously written. Move new Array() (or better [] , the array literal) outside the loop

 var all = [];
    for (i = 0; i <= 4; i++) {
      let element = i;
      all.push(element);
    }
    alert(all[1]);
    alert(all[2]);
    alert(all[3]);
    alert(all[4]);

Try some thing like:

const Coin = [
  "Heads",
  "Tails"];

You are recreating the array on each iteration. Try this:

var all = []; // Moved up, and replaced with bracket notation.
var a = 1;
for(i=0;i<4;i++)
{
all[i]=a;
a++;
}

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

Your issue here is that you're reinstantiating a new Array on each iteration of the loop. So, the first time around, you set a value in that array. The second time around, you redefine the all variable to be a completely new array, which undoes the work you did in the last iteration.

The easiest thing to do is just move var all = new Array() and put it before your loop.

You are redefining your array inside the for loop. You need to define it outside.

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]);
var a = 1;
var all = new Array();
for(i=0;i<4;i++)
{


all[i]=a;
a++;
}

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

You need to put var all = new Array() outside your loop. You're creating a new all[] four times.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM