Я потратил 3 часа на то, чтобы исправить цикл for. Я пробовал все ... Если я удалю оператор switch/if, цикл for работает нормально. Пожалуйста, порекомендуйте.Оператор switch/if прерывает цикл for
Этот код нормально. Здесь я объявляю объекты и функции.
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
переключая СДЕЛАНО
Почему обыкновение две другие инструкции огонь?
Вместо/в дополнение к переименовав переменную, вы действительно должны объявить его как 'для (вар я = 0; ...' Итак, когда вы добавьте переменную 'z' где-то еще в вашем коде, она не сломается снова. –