switch/if语句中断了for循环
The switch/if statement breaks the for loop
到目前为止,我已经花了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;...;...)
相关文章:
- 为什么JavaScript在for循环为3时向所有4发出警报
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 我的javascript for循环不起作用
- For循环冻结Javascript
- 如何在for循环中添加事件侦听器
- 双“for”循环(循环)
- javascript for循环不起作用
- for循环中的javascript if语句找不到==
- Javascript在for循环中等待处理请求
- For循环在Jquery中只运行一次
- 如何在for循环中使用计数器
- for循环中的JavaScript闭包
- 为什么我们在ES2015中需要一个新的for循环结构,而我们已经有了for、forEach
- For循环在调用时未运行
- 如何使用for循环添加所有按钮'单击事件
- 如何更改在for循环中生成的圆的位置
- 为什么这个For循环会使浏览器实验室崩溃
- 为什么我使用javascript获得了一个无限的for循环
- 在for循环中使用多维数组设置google.maps.Marker图标
- 如何在angularJS中运行for循环而不使用html标记