I've spent 3 hours so far trying to fix the for loop. I've tried everything... If I remove the switch/if statement, the for loops works fine. Please advise.
This code is ok. I declare the objects and functions here.
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");
}
This is the problematic part. I have no idea why it won't work.
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;
}
}
Output:
Instructions populated.
Grid populated.
For Loop start
toggle 461 550 564 900
Toggling DONE
Why wont the other two instructions fire?
Aucun commentaire:
Enregistrer un commentaire