0

我正在尝试从循环内部更新存在于循环外部的变量,如下所示:

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 once3 次。相反,我得到This is your first run了 4 次,并且console.log("firstRun is " + firstRun);总是输出true

我确定这是我不太了解的范围问题。原谅我,我来自红宝石的土地:)

4

4 回答 4

3

您正在重新声明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");
};
于 2013-01-31T01:20:10.653 回答
0

如果整个块在您的循环中,您将在每次迭代时重置 var firstRun = true 。您需要在循环之外设置 var firstRun = true (为了清楚起见,就在它之前)。

var firstRun = true;
for (var i = 0; i < 4; i++) {
    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");
    };
}
于 2013-01-31T01:23:34.417 回答
0

我假设布尔值在每次迭代时都会被重置。移动var firstRun = true;外循环!

var firstRun = true;
for (...) {
  if(firstRun){firstRun=false;}
  else{}
}
于 2013-01-31T01:20:29.540 回答
0

firstRun您每次都在循环中重置变量,因此当条件语句执行时,值firstRun将始终为true.

你需要做这样的事情

var firstRun = true;

//Loop only following block
if(firstRun == true){
    console.log("This is your first run");
    firstRun = false;
}else{
    console.log("You have already run this loop at least once");
};
于 2013-01-31T01:20:49.483 回答