问题
Can anybody explain to me how this casue an infinite loop? I got this from an example of a javascript book.
The code is as follows:
function foo() {
function bar(a) {
i = 3; // changing the `i` in the enclosing scope's for-loop
console.log( a + i );
}
for (var i=0; i<10; i++) {
bar( i * 2 ); // oops, inifinite loop ahead!
}
}
foo();
回答1:
The problem is, that you're changing i from the for-loop inside your bar function
i = 3;
That means outside of bar it can't reach the condition i < 10.
So the calls of bar would be like:
bar(0 * 2);theni = 3;thenconsole.log(0 + 3);theni++bar(4 * 2);theni = 3;thenconsole.log(8 + 3);theni++bar(4 * 2);theni = 3;thenconsole.log(8 + 3);theni++- and so on...
iwill stay smaller than 10
You should change your code to avoid the set of i = 3;, which is the root of your problem.
来源:https://stackoverflow.com/questions/55260180/for-loop-infinite-loop-due-to-variable-collision