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]);
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.
Share Improve this question edited Nov 30, 2023 at 15:46 isherwood 61.1k16 gold badges120 silver badges168 bronze badges asked Mar 30, 2012 at 23:15 vishnu Simbuvishnu Simbu 431 gold badge4 silver badges10 bronze badges9 Answers
Reset to default 10You 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]);
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]);
Try some thing like:
const Coin = [
"Heads",
"Tails"];