我正在尝试像这样从循环内部更新循环外部存在的变量:

var firstRun = true;
console.log("firstRun is " + firstRun);
if(firstRun == true){
    console.log("This is your first run");
    firstRun = false;
}else{
    console.log("You have already run this loop at least once");
};


假设此代码块在可以运行4次的较大代码块之内,我希望它输出一次This is your first run,然后输出You have already run this loop at least once 3次。相反,我得到This is your first run 4次,并且console.log("firstRun is " + firstRun);始终输出true

我确定这是我不太了解的范围问题。原谅我,我来自露比(Ruby):)

最佳答案

您要在循环的每个步骤中重新声明firstRun。将var firstRun = true;移出循环。

如果无法将其移出循环,则必须使用一个对象,并在分配该对象之前检查是否已声明该对象:

var firstRun = firstRun || {ran: false};

if (firstRun.ran == true) {
    console.log("This is your first run");
    firstRun.ran = false;
} else {
    console.log("You have already run this loop at least once");
};

10-04 15:32