+ 1
JavaScript
I do not understand how this works, please someone help me out. var arr = [1,2,3,4]; var length = arr.length; for (var i = 0; i < length; i++){ length--; document.write(arr[i]); } answer is 12 but I have no idea how we got here please can someone explain it to me. Thank you in advance.
1 Odpowiedź
+ 3
Kelvin Wambua
1st iteration of loop:
length = 4, I =0
length = length -1 = 3
arr [I] = arr[0] =1//it will be printed
2nd iteration of loop:
length = 3, I = 1
length = length - 1 = 2
arr[I] = arr[1] = 2 // it will be printed
3rd iteration of loop:
length = 2, I = 2
So the condition
( I < length ) will be false and loop will be terminated.
That's why the output is 12