I'm a newbie in JavaScript programming. At our university we were just beginning to learn about JavaScript loops. So here's a code using for loop:
var i;
var x = new Array();
var y = new Array(1, 1, 0, 3, 5);
for (i = 0; i < y.length; i++) {
x[y[i]] = y[i];
}
I know that such code produces variable x to be an array with values
0, 1, undefined, 3, undefined, 5
I do not understand the logic behind it. Can somebody please help me?
5 Answers 5
Let's first simplify this a bit and expand to make it more legible:
var x = new Array();
var y = new Array(1, 1, 0, 3, 5);
for(let i = 0; i < y.length; i++){
let key = y[i];
x[ key ] = y[i];
}
On first evaluation, i === 0, so key === y[0] or 1. Now that we have the key, we will assign the key as a value to the x array at the index that was the number stored in your y array at index i. So x[y[0]] = y[0], therefor x[1] === 1.
Wrince, repeat.
1 Comment
Okay let's loop through that one by one:
i=0
x[1] = 1 //because y[0] = 1
i=1
x[1] = 1 //because y[1] = 1
i=2
x[0] = 0 //because y[2] = 0
i=3
x[3] = 3 //because y[3] = 3
i = 4
x[5] = 5 //because y[4] = 5
So you've set values in x for indices 0, 1, 3 and 5, but not 2 and 4, that's why those values are undefined
1 Comment
You have to realize that the positions where data is put in Array X are taken from Array Y.
As Array Y only have the following numbers (it means, positions): 0, 1, 3, 5, the positions 2 and 4 will be undefined in the Array X
var i;
var x = new Array();
var y = new Array(1, 1, 0, 3, 5);
for (i = 0; i < y.length; i++) {
console.log("Index taken from ARRAY Y where number will be put in ARRAY X: " + y[i]);
x[y[i]] = y[i];
}
1 Comment
Because you are not incrementing it by the index. You are setting the index based on the value of the index of the y array.
So what you are doing in your loop is
x[1] = 1 // i = 0;
x[1] = 1 // i = 1;
x[0] = 0 // i = 2;
x[3] = 3 // i = 3;
x[5] = 5 // i = 4;
There is no value of 2 or 4, so those indexes were never defined, so it it is undefined.
What you want is
for (i = 0; i < y.length; i++) {
x[i] = y[i];
}
1 Comment
Try to write down each iteration and see how x changes in successive steps.
START // []
x[y[0]] = y[0]; // x[1] = 1; [undefined, 1]
x[y[1]] = y[1]; // x[1] = 1; [undefined, 1]
x[y[2]] = y[2]; // x[0] = 0; [0, 1]
x[y[3]] = y[3]; // x[3] = 3; [0, 1, undefined, 3]
x[y[4]] = y[4]; // x[5] = 5; [0, 1, undefined, 3, undefined, 5]
i=0->x[1]=1, i=1->x[1]=1, i=2->x[0]=0, i=3->x[3]=3, i=4->x[5]=5so x[2] and x[4] is never set