+ 8

Поясните пожалуйста почему так работает цикл? На выходе получаем 1334 / Explain the output of this code? Why output 1334?

var arr=[1, 2, 3, 4]; var ct=arr.length; for (var i=0; i<ct; i++) { ct--; arr[i]+=i; } document.write(arr);

2nd Apr 2018, 10:10 PM
🕸carpe diem🕸
🕸carpe diem🕸 - avatar
4 Answers
+ 10
I understand, 1 and 2 it's result of loop and 3, 4 elements of array that don't delete. Thank you👌
2nd Apr 2018, 10:45 PM
🕸carpe diem🕸
🕸carpe diem🕸 - avatar
+ 1
1+0 = 1 2+1 = 3 Then it exits from the loop since ct is 2 and i is 2 too meaning that i < ct is false.
2nd Apr 2018, 10:19 PM
Kevin Eldurson
Kevin Eldurson - avatar
+ 1
Let's go through the code, as if we were a run-time debugger: arr=[1, 2, 3, 4] ct = 4 for (var i=0; i<4; i++) { ct-- // i = 0 // ct = 3 arr[0] = arr[0] + 0 = 1 + 0 = 1 for (var i=1; i<3; i++) { ct-- // i = 1 // ct = 2 arr[1] = arr[1] + 1 = 2 + 1 = 3 for (var i=2; i<2; i++) { break; document.write(arr); Note that only the first two elements of the array are overwritten, as 1 and 3 respectively. In the future, you can put more document.write() functions to see what's happening. You can also do what I did, which is to step through it, like a debugger would.
2nd Apr 2018, 10:27 PM
Emma
- 1
Yes, that's exactly it.
2nd Apr 2018, 10:55 PM
Emma