'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
Solution 1:[1]
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
Solution 2:[2]
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]);
Solution 3:[3]
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]);
Solution 4:[4]
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.
Solution 5:[5]
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]);
Solution 6:[6]
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]
Solution 7:[7]
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]);
Solution 8:[8]
Try some thing like:
const Coin = [
"Heads",
"Tails"];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dennis |
| Solution 2 | |
| Solution 3 | Danny Kirchmeier |
| Solution 4 | Kevin Ennis |
| Solution 5 | John W |
| Solution 6 | snoofkin |
| Solution 7 | Eric Bridger |
| Solution 8 | Stephen Rauch |
