The following code, I thought it would output 1-10, but the output is 5, and it keeps outputting 5. It is an infinite loop. I don’t understand it. Please enlighten me. Thanks!
function initloop() {
function doLoop(x) {
i = 3;
console.log(x);
}
for (var i = 0; i < 10; i++) {
doLoop(i + 1);
}
}
initloop();
光陰似箭催人老,日月如移越少年。
That i is actually equivalent to being declared in initloop.
function initloop() {
var i = 0;
function doLoop(x) {
i = 3;
console.log(x);
}
for ( ; i < 10; i++) {
doLoop(i + 1);
}
}
initloop();
Look at it this way, if you think about the function execution process, you should understand.
Every time it loops, i will be modified to 3 in doloop.
After doloop is executed, i++ is executed, and the actual parameters passed into the loop should be It's 4 + 1;
So the console first is 1, and then it keeps outputting 5 in an infinite loop.
If you want to output 1 - 10 as you want, add var to i in the doloop. Make it a local variable.
The first loop i=0, the doloop actual parameter i+1 is 1, so the first output is 1. Because there is no i variable in the doloop function, it will look for the i variable in the external scope, so i=3 will assign the value of i in the loop body to 3. After the first loop ends, because i<10, i++ is 4. Starting from the second time, i is 4, so the dooloop actual parameter is 5. Because i is assigned a value of 3 every time the dloop function is executed, so i is always less than 10. The result is 1 for the first time, and then prints 5 in a loop.
First I tried running your code, and the browser got stuck twice... I mourned for my browser...
For this reason, I discovered that your code is poisonous...
When actually running, the input is as follows:
The first time in the for loop, i===0
, 執(zhí)行doLoop(1)
, 因此doLoop
函數(shù)內(nèi)部, 形參x===1
, 接著又改變了外部i的值, 重置為3
, 故此時i===3
, 緊接著打印出了x的值, 即1
.
When the for loop loops for the second time, because the first loop endsi===3
, 發(fā)生自增操作, 即i++
. 故i最終等于4
. 4+1=5
, 故執(zhí)行doLoop(5)
,本次打印出了5
. 函數(shù)內(nèi)部重復(fù)上一次的操作, 外部i變量再次被重置為3
,本次循環(huán)結(jié)束后i===5
.
When the for loop loops for the third time, the last operation is repeated, i is reset to 3
, 再次打印5
, 以此類推, 最終外層的for循環(huán)失效, 每次i的值都被重置為3
again, and the loop end condition cannot be met. Therefore, the loop cannot exit. Therefore, the browser freezes.
To summarize, this way of writing is problematic. Try not to change variables outside the function inside the function.
Every time the loop loops, i is assigned a value of 3, and i in the dloop function is not a private variable, so i in the initloop is assigned a value of 3 every time. The next time i++ is looped, i becomes 4 and passed into the dloop. Naturally, every printed value is 5. After solving it, dloop changes i to 3. i will never be equal to 10, so the loop is endless