[英]javascript loop not giving expected results
Okay so I haven't touched JS in a long time, and need a little help with a simple loop. 好的,所以我已经很长时间没有接触过JS了,因此需要一个简单循环的帮助。 I am building a checkers game.
我正在建立一个跳棋游戏。 Here is the code so far:
这是到目前为止的代码:
checkerboard = [[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null]];
function setSquare(player, row, col) {
// which places a player (either 'R' or 'B') at a particular row and column on the board.
checkerboard[row][col] = player;
return checkerboard[row][col];
}
function getPieceAt(row, col) {
//returns the piece at a particular row and column if there's no piece at that position, it should return null//
return checkerboard[row][col] || null;
}
function clearBoard(array){
for(var i = 0; i < array.length; i++){
var subArray = i;
for(var x = 0; x < subArray.length; x++){
subArray[i][x] = 'hello';
}
}
}
The clearBoard function does not work. clearBoard功能不起作用。
The function is supposed to revert all the values of the array to null. 该函数应该将数组的所有值还原为null。
Problem: It doesn't seem to be doing anything and I don't see whatever it is I am missing. 问题:它似乎什么也没做,我也看不到我所缺少的东西。 I tried it with a return, returning 'array', but it didn't work so I took it out thinking maybe it was calling the original hardcoded array (checkerboard - full of null values).
我尝试了一个返回,返回'array',但没有成功,所以我以为可能是在调用原始的硬编码数组(棋盘-包含空值)。 What's wrong with my loop?
我的循环怎么了?
// For the sake of easier testing, I am having it do the opposite for the time being (otherwise I have to keep setting values to something other that null using the setSquare function every time I save and re-run the code, because the environment I am using reverts everything back to original/null. It's tedious.) Once the code can set all the values to "hello", I know it can set them to null. //为了简化测试,我暂时将其设置为相反(否则,每次保存并重新运行代码时,都必须使用setSquare函数将设置为null的值设置为null,因为我正在使用的环境将所有内容还原为原始值/空值。这很乏味。)一旦代码可以将所有值设置为“ hello”,我知道它可以将其设置为null。 //
//
i is a number. 我是一个数字。 you are assigning subarray to that number.
您正在为该数字分配子数组。
function clearBoard(array){
for(var i = 0; i < array.length; i++){
var subArray = i; // subarray goes 0, 1, 2, 3, ... not an array but a number
for(var x = 0; x < subArray.length; x++){
subArray[i][x] = 'hello'; // your indexing too much.
}
}
}
I think this will work better for you 我认为这对您会更好
function clearBoard(array){
var subArray;
for(var i = 0; i < array.length; i++){
subArray = array[i];
for(var x = 0; x < subArray.length; x++){
subArray[x] = null; // this will bring you back to the beginning state
}
}
}
call it like this. 这样称呼它。
clearBoard(checkerboard);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.