switch/if语句中断了for循环

The switch/if statement breaks the for loop

本文关键字:for 循环 中断 语句 if switch      更新时间:2023-09-26

到目前为止,我已经花了3个小时试图修复for循环。我什么都试过了。。。如果我删除switch/If语句,for循环就可以正常工作。请告知。

上下文:这是一个练习,必须按照一组带有坐标的说明打开/关闭1000x1000个灯光的栅格。

这段代码可以。我在这里声明对象和函数。

var data = ["toggle 461,550 through 564,900", "turn off 370,39 through 425,839", "turn on 599,989 through 806,993"];
var instructions = []; //301
for(i = 0; i < data.length; i++){
var instruction = data[i].match(/'d+/g);
    if(data[i].match(/on/)) instruction.splice(0, 0, "on")
    else if(data[i].match(/off/)) instruction.splice(0, 0, "off")
    else if(data[i].match(/toggle/)) instruction.splice(0, 0, "toggle")
    instructions.push(instruction);
    console.log("Instructions populated.");
}
function Light(x, y, s) { // Constructor
    this.x = x;
    this.y = y;
    this.s = s;
}
var lights = []; // The grid
for(x = 0; x < 10; x++) {// Populates the grid
    for(y = 0; y < 10; y++) {
        lights.push(new Light(x, y, false));
    }
    console.log("Grid populated.");
}
function turnOn(x1, y1, x2, y2) {
    for (i = 0; i < lights.length; i++) {
        if(lights[i].x >= x1 && lights[i].x <= x2 
        && lights[i].y >= y1 && lights[i].y <= y2) {
            lights[i].s = true;
        }
        //console.log(lights[i]);
    }
    console.log("Turning on DONE");
}
function turnOff(x1, y1, x2, y2) {
    for (i = 0; i < lights.length; i++) {
        if(lights[i].x >= x1 && lights[i].x <= x2 
        && lights[i].y >= y1 && lights[i].y <= y2) {
            lights[i].s = false;
        }
    }
    console.log("Turning off DONE");
}
function toggle(x1, y1, x2, y2) {
    for (i = 0; i < lights.length; i++) {
        if(lights[i].x >= x1 && lights[i].x <= x2 
        && lights[i].y >= y1 && lights[i].y <= y2) {
            lights[i].s = !lights[i].s;
        }
    }
    console.log("Toggling DONE");
}

这是有问题的部分。我不知道为什么它不起作用。

console.log("For Loop start");
for(i = 0; i < instructions.length; i++){
    var action = instructions[i][0];
    var x1 = instructions[i][1];
    var y1 = instructions[i][2];
    var x2 = instructions[i][3];
    var y2 = instructions[i][4];
    console.log(action, x1, y1, x2, y2);
    switch(action){ // This breaks the loop.
        case "on": 
            turnOn(x1, y1, x2, y2); 
            break;
        case "off": 
            turnOff(x1, y1, x2, y2); 
            break;
        case "toggle": 
            toggle(x1, y1, x2, y2); 
            break;
    }
}

输出:

指令已填充
网格已填充
循环启动
切换461 550 564 900
Toggling DONE

为什么其他两个指令不会启动

function toggle(x1, y1, x2, y2) {
    for (i = 0; i < lights.length; i++) {

toggle重用i,并且由于此函数中没有var i,因此它从外部范围使用i。也就是说,你的循环。

在for循环中使用全局变量i,在toggle()函数中使用相同的变量,因此循环结束。

将所有for循环更改为:

for(var i=0;...;...)