for-loop infinite loop due to variable collision

感情迁移 提交于 2021-01-28 05:48:33

问题


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:

  1. bar(0 * 2); then i = 3; then console.log(0 + 3); then i++
  2. bar(4 * 2); then i = 3; then console.log(8 + 3); then i++
  3. bar(4 * 2); then i = 3; then console.log(8 + 3); then i++
  4. and so on... i will 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!