+ 1

JS challenge question

var x =[2,3,2,5]; for(var i = 0; i<x.length-1; i++) { x[i]=x[i+1]; } document.write(x); Output is 3,2,5,5 Please, help me to understand why we have such output? If we put document.write(x) inside the cycle we will have the following iterations; 3,3,2,5 3,2,2,5 3,2,5,5 I can not understand why. How does it work? Thank you for your help.

31st Oct 2017, 1:55 PM
Olga Slavova
Olga Slavova - avatar
4 odpowiedzi
+ 2
Step 1: i=0, which is less than the array's length. So the first element becomes 3 Step 2: i=1, which is lessvthan the array's length. So the second element becomes 2 Step 3: i=2, which is less than the array's length. So the third element becomes 5 Step 4: i=3, which is equal to the array's length. So the fourth element remains unchanged.
31st Oct 2017, 2:17 PM
DAB
DAB - avatar
+ 1
var x =[2,3,2,5]; var t=x[0]; for(var i = 0; i<x.length-1; i++) { x[i]=x[i+1]; } x[x.length-1]=t; document.write(x); This will rotate the array giving output of 3,2,5,2
31st Oct 2017, 2:50 PM
John Wells
John Wells - avatar
+ 1
Thank you, guys!
31st Oct 2017, 7:13 PM
Olga Slavova
Olga Slavova - avatar
0
1: var x =[2,3,2,5]; 2: for(var i = 0; i<x.length-1; i++) { 3: x[i]=x[i+1]; 4: } Line 1 sets x to 2,3,2,5 Line 2 sets i to 0 Line 3 copies x[0+1] to x[0] replacing 2 with 3 (3,3,2,5) Line 4 goes back to 2. Line 2 sets i to 1 Line 3 copies x[1+1] to x[1] replacing 3 with 2 (3,2,2,5) Line 4 goes back to 2. Line 2 sets i to 2 Line 3 copies x[2+1] to x[2] replacing 2 with 5 (3,2,5,5) Line 4 goes back to 2. Line 2 sets i to 3; it is now = to x.length-1 so goes to Line 5
31st Oct 2017, 2:46 PM
John Wells
John Wells - avatar