I really need a answer and a practice link to fully understand loop like this in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

I really need a answer and a practice link to fully understand loop like this in JavaScript

var x =[12345] for(var i=0; i<4;i++){ x[i]=x[i+1] if(i==x.length-2){ x[i]=x[0] } } alert(x)

2nd Aug 2018, 8:46 PM
George S Mulbah II
George S Mulbah II - avatar
13 Answers
+ 7
George S Mulbah right I forgot JS cra... logic. XD
3rd Aug 2018, 12:46 AM
LONGTIE👔
LONGTIE👔 - avatar
+ 5
George S Mulbah I would guess I don't know JavaScript.
3rd Aug 2018, 12:13 AM
LONGTIE👔
LONGTIE👔 - avatar
+ 4
George S Mulbah if i is equal to x's length minus 2
2nd Aug 2018, 11:27 PM
LONGTIE👔
LONGTIE👔 - avatar
+ 3
LONGTIE will the array length be reduce by 2
2nd Aug 2018, 11:41 PM
George S Mulbah II
George S Mulbah II - avatar
+ 3
thanks mahn but this course is way more complicated because eg ("5"-1)=4 but ("5"+1)=51 you see why we can not assume any thing in JavaScript accept we know it
3rd Aug 2018, 12:42 AM
George S Mulbah II
George S Mulbah II - avatar
+ 2
It is code for rotate array to the left and finally after if() it adding first element to the end of array. Try this correct version with output for each step of changing array: var x =[1,2,3,4,5]; var x0 = x[0]; document.write(x +"<br>for"); for(var i=0; i<4; i++){ x[i] = x[i+1]; if(i==x.length-2){ document.write("<br>"+ x +"<br>if"); x[i+1]=x0; } document.write("<br>"+ x); } alert(x); /* output: 1,2,3,4,5 for 2,2,3,4,5 2,3,3,4,5 2,3,4,4,5 2,3,4,5,5 if 2,3,4,5,1 */
5th Aug 2018, 1:52 AM
zemiak
+ 1
Choubada ,Sir Can you elaborate more on your answer please, I am still not understanding
2nd Aug 2018, 8:58 PM
George S Mulbah II
George S Mulbah II - avatar
+ 1
the variable named i, in our loop will be our array indexer. The begin of our loop: i = 0 so x[i] equals to 1. etc etc.. And, for each number in the array, we add one to it. So, after the loop, x is equal to [2,3,4,5,6]
2nd Aug 2018, 9:01 PM
Chalza
Chalza - avatar
+ 1
thank a lot ,so we are incrementing each number in the array by 1 is that right ,upon the execution of our loop
2nd Aug 2018, 11:23 PM
George S Mulbah II
George S Mulbah II - avatar
+ 1
but what is the meaning of if(i==x.length-2)
2nd Aug 2018, 11:25 PM
George S Mulbah II
George S Mulbah II - avatar
0
X has one only index, you should use , between yout numbers. Your loop: So, for each element of array x, assign its value to the next element of the array. Pretty simple :)
2nd Aug 2018, 8:48 PM
Chalza
Chalza - avatar
0
zemiptark could you
7th Aug 2018, 1:11 PM
George S Mulbah II
George S Mulbah II - avatar
0
zemiah could you elaborate more on the for loop and if statement
7th Aug 2018, 1:12 PM
George S Mulbah II
George S Mulbah II - avatar