Javascript 程序未进入for循环
我目前在高中上计算机科学课,正在编写一个程序来模拟康威的生活游戏。我正在CodeStudio“AppLab”中编写这个程序,它使用JavaScript,这也是我们一直在学习的内容。它的左边有一个智能手机,你可以为它设计 到目前为止,一切都很顺利,但我正在努力在屏幕上绘制单元格,而我的程序拒绝进入for循环,该循环将绘制单元格(以按钮表示)。绘制CellBoard的函数称为drawBoard,是CellBoard对象内部的一个方法Javascript 程序未进入for循环,javascript,Javascript,我目前在高中上计算机科学课,正在编写一个程序来模拟康威的生活游戏。我正在CodeStudio“AppLab”中编写这个程序,它使用JavaScript,这也是我们一直在学习的内容。它的左边有一个智能手机,你可以为它设计 到目前为止,一切都很顺利,但我正在努力在屏幕上绘制单元格,而我的程序拒绝进入for循环,该循环将绘制单元格(以按钮表示)。绘制CellBoard的函数称为drawBoard,是CellBoard对象内部的一个方法 function Cell(x, y, id) { //bas
function Cell(x, y, id) {
//base unit for the program, can be either dead or alive based on Conway's
//Game of Life Rules
this.xPos = x;
this.yPos = y;
this.id = "cell" + id;
this.alive = false;
this.aliveNextTurn = false;
this.aliveNeighbors = 0;
this.age = 0;
this.swapState = function(){
if(this.alive){
this.alive = false;
}
else{
this.alive = true;
}
};
}
function CellBoard(width, height){
//the board of cells, this object will house all the methods for the rule
//checking and state setting
this.board = [];
var count = 0;
for(var x = 0; x<width; x++){
var boardY =[];
for(var y = 0; y<height; y++){
boardY.push(new Cell(x,y,count));
count++;
}
this.board.push(boardY);
}
this.drawBoard = function(){
//draws the board of cells on the screen as buttons so that the user can
//initially set them
setScreen("simulationScreen");
//console.log("screen set");
//console.log("starting button making");
for(var i = 0; i<this.width; i++){ //<----the problem is here
//console.log("starting loop");
for(var j = 0; j<this.height; j++){
//console.log("making button");
button(this.board[i][j].id, "test");
setPosition(this.board[i][j].id, 20+(280/i), 20+(280/j), 280/i, 280/j);
setProperty(this.board[i][j].id, "background-color", rgb(0,0,0)); //black background by default
//console.log(getProperty(this.board[i][j].id, "x"));
}
}
//console.log("done drawing board");
};
}
var testBoard = new CellBoard(3, 3);
testBoard.drawBoard();
在
drawBoard
函数中的for循环中,使用this.width
和this.height
。但是,您从未设置此.width
和此.height
。在CellBoard类的初始化代码中,您应该设置this.width=width
。它可能跳过for循环,因为此.width
未定义,不满足for循环条件
此外,您还可以在
drawBoard
函数中使用this
关键字。在这样的函数中,此
将引用函数而不是对象。相反,在初始化代码中,您可能需要创建一个变量来保存此。您可以在初始化代码中执行cell\u board=此操作
,然后在drawBoard
功能中使用cell\u board.width
。如果您向我们扔代码并抱怨“它不起作用!”您很可能会受到不好的待遇。你应该阅读FAQ以获得如何提出适当问题的建议。如果你打电话给cellBoard,它必须进入for循环,你只是没有得到你期望的结果。您看过控制台输出了吗。您可以添加一些控制台日志,以找出哪里出了问题。@Difster它进入函数,然后更改屏幕,然后跳过for循环,我将添加控制台日志,而调试未注释。
screen set
starting button making
done drawing board