For loop var 保留 for 循环中的 var 值,可能关闭?

For loop var retains var value from for loop, possible closure?

我正在为一个名为 illustrator 的程序编写一些代码,您可以使用它 JavaScript。这让我发疯,我认为这与关闭有关,但我不确定是不是还是我只是遗漏了一些东西。

我有以下代码:

function runSomeStuff() {
  // some stuff gets done here unrelated variables set
  // after I have the following for loop which opens the document

  for (var currentTemplate = 1; currentTemplate <= 3; currentTemplate++){

    // opens file and does a few if statements... works fine.
    // here I have another for loop where the problem comes up
    for (var i = 1; i <= 18; i++) {
      // run some code here
    }
  }

}

它应该工作的方式是它应该在包含另一个 for 函数的第一个 for 函数上循环 3 次。所以它应该像这样工作。

第一个函数 运行s

第二次在第一个 运行 内执行 17 次然后退出,执行所需的操作然后再次开始 运行。

问题是在第一个函数 运行s 之后,当它再次循环时它不会 运行。第二个 for 函数不再 运行 。我为 var i 添加了一个警报,它在第二次尝试 运行 时给了我 19。我希望 var i 再次为 1,因为它在第二个 运行 上被重新调用。它甚至在它存在之后出现,当它在 for 循环中时我保留它的值所以它是假的,因为我将大于 18。

编辑:由于正在使用的程序,我不能使用 let 或 const。

可能发生这种情况的原因是 variable hoisting。如果您在函数的第一行声明变量,我建议检查是否有任何变化:

function runSomeStuff() {
  var currentTemplate, i;

  // some stuff gets done here unrelated variables set
  // after I have the following for loop which opens the document

  for (currentTemplate = 1; currentTemplate <= 3; currentTemplate++){

    // opens file and does a few if statements... works fine.
    // here I have another for loop where the problem comes up
    for (i = 1; i <= 18; i++) {
      // run some code here
    }
  }
}

如果上述方法不起作用,您可能想尝试管理自己的作用域,方法是将 for 循环移动到 IIFEs:

function runSomeStuff() {
  // some stuff gets done here unrelated variables set
  // after I have the following for loop which opens the document

  (function () {
    for (var currentTemplate = 1; currentTemplate <= 3; currentTemplate++){

      // opens file and does a few if statements... works fine.
      // here I have another for loop where the problem comes up
      (function () {
        for (var i = 1; i <= 18; i++) {
          // run some code here
        }
      })();
    }
  })();
}

这会把事情搞得一团糟,但是你的循环将有自己的范围,而不需要使用 let 关键字。

发生这种情况的原因很可能是变量作用域。这意味着您的变量在声明时被移动到函数的顶部。为避免这种情况,您可以通过以下方式声明变量:

let i = 0;
let str = "Hello";
let arr = [1, 2, 3];

let 允许你的变量在第一次提到时被声明,并且应该清除 问题。我一直使用 let,我的范围问题已经消失了。