我正在尝试更新循环内循环之外的变量,如下所示:
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
三次。相反,我得到This is your first run
4次而console.log("firstRun is " + firstRun);
总是输出true
我确定这是一个范围问题,我不太明白。原谅我,我来自Ruby的土地:)
答案 0 :(得分: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");
};
答案 1 :(得分:0)
我假设每次迭代都会重置布尔值。将var firstRun = true;
移到循环外面!
var firstRun = true;
for (...) {
if(firstRun){firstRun=false;}
else{}
}
答案 2 :(得分: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");
};
答案 3 :(得分: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");
};
}