我正在对一个名为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
}
}
}
它应该工作的方式是它应该在第一个循环3次,用于包含另一个函数的函数。所以它应该像这样工作。
首先是函数运行
第二次内部第一次运行17次然后退出,它需要什么然后开始再次运行。
问题是在第一个函数运行一次之后,当它再次循环时它将不会运行。功能的第二个不再运行。我为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,我的范围问题已经消失。