为什么全局变量在嵌套while循环(内部)中仅执行一次?
//not working as expected;
var i = 1;
var j = 1;
while(i<=3){
console.log(i);
i++;
while(j<=3){
console.log(j);
j++;
}
}
//working as expected;
var i = 1;
while(i<=3){
console.log(i);
i++;
var j = 1;
while(j<=3){
console.log(j);
j++;
}
}
答案 0 :(得分:2)
这是因为j
不会被重新分配,一旦变为> 3,就不会执行内部循环。
//not working as expected;
var i = 1;
var j = 1;
while(i<=3){
console.log(i);
i++;
while(j<=3){
console.log(j);
j++;
}
}
在此代码中,在外循环的第一次迭代期间,当1 to 3
时j从i = 1
开始递增。当i = 2
时,j已经为4
并且没有被重新分配,因此条件j <= 3
为false并且不执行内部循环。
答案 1 :(得分:0)
TLDR:如果每次迭代都是全局的,则j不会重新分配回1。
当j变量是全局变量时,不会在每个循环中将其重置为1。
outer loop output: i = 1
inner loop output: j = 1
inner loop output: j = 2
inner loop output: j = 3
outer loop output: i = 2
outer loop output: i = 3
当j变量位于第一个while循环内时,它将在每次迭代时重置以输出,如下所示...
outer loop output: i = 1
inner loop output: j = 1
inner loop output: j = 2
inner loop output: j = 3
outer loop output: i = 2
inner loop output: j = 1
inner loop output: j = 2
inner loop output: j = 3
outer loop output: i = 3
inner loop output: j = 1
inner loop output: j = 2
inner loop output: j = 3
答案 2 :(得分:0)
因为您没有将值改回1 试试这个:
var i = 1;
var j = 1;
while(i<=3){
console.log(i);
i++;
while(j<=3){
console.log(j);
j++;
}
j = 1;
}