Okay so I haven't touched JS in a long time, and need a little help with a simple loop. 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.
The function is supposed to revert all the values of the array to 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). 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. //
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.