JavaScript中的双循环

Dan*_*ski 6 javascript

var
startx = 0,
starty = 0,
endx = 12,
endy = 100;

for(startx;startx <= endx; startx+=1){
        for(starty; starty <= endy; starty+=1){
            console.log(startx, endx, starty, endy);
     }
}
Run Code Online (Sandbox Code Playgroud)

预期产量:

0, 12, 0, 100
0, 12, 1, 100
0, 12, 2, 100
...
0, 12, 100, 100
1, 12, 0, 100
1, 12, 1, 100
...
12, 12, 100, 100
;EOO
Run Code Online (Sandbox Code Playgroud)

Chrome 39+上的输出

0, 12, 0, 100
0, 12, 1, 100
0, 12, 2, 100
...
0, 12, 100, 100
Run Code Online (Sandbox Code Playgroud)

所以问题是第一个for循环不会遍历startx变量.

你能告诉我它为什么不迭代吗?

and*_*lrc 14

这是一个有趣的谜题.在我抓住它之前我花了几次.

原因是starty在第一次迭代后没有重置,因此第二个for循环只运行一次,因为条件总是为假.

你要:

var startx = 0,
    starty = 0,
    endx = 12,
    endy = 100;

for (; startx <= endx; startx++) {
    for (starty = 0; starty <= endy; starty++) {
        console.log(startx, endx, starty, endy);
    }
}
Run Code Online (Sandbox Code Playgroud)

我也简化startx+=1startx++,同样的starty.

我还建议养成var自己编写每个语句的习惯:

var a;
var b;
Run Code Online (Sandbox Code Playgroud)

这使得在调试时更容易停止.尝试踩进去,def()不要踩到abc().

var a = abc(),
    b = def();
Run Code Online (Sandbox Code Playgroud)

for循环如何分解:

for循环分为3部分:

for(initial; condition; after)
Run Code Online (Sandbox Code Playgroud)

initial在循环之前调用,可以安全地省略.
condition在循环中运行代码之前调用,如果
after在循环中的代码与写入相同后调用省略,则始终为true :

for(var i = 0; i < 10;) {
  // code
  i++;
}
Run Code Online (Sandbox Code Playgroud)