I have recently gotten started in using the JavaScript programming language. No, this is not my first language, but this is one of my first time using it. I am trying to create a chess program using the HTML5 canvas capability. I am using a for loop to create an array of all of the positions for the chess pieces. I run into one problem; it stores all of the coordinates as undefined. Bellow is the code for the functions that store these values.
var board = [];
function createBoard() {
var integer = 0;
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
board[integer] = new Position(i, j);
integer++;
}
}
}
function replacePosition(position1, position2) {
var i = board.indexOf(position1);
board[i] = position2;
}
function getPosition(x, y) {
for (var position in board) {
console.log("(" + position.x + "," + position.y + ")");
if (position.x == x && position.y == y) {
return position;
}
}
return null;
Here is the Position class if you need it.
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
this.piece = null;
}
}
I run createBoard(), and then I attempt to use getPosition(). I says that my code does not work with a null value. If I look at the console, it keeps logging "(undefined,undefined)." I did a little research, but the only thing I could find was asynchronous. I tried to look into that, but I could not figure out how to fix it. Does anyone know how to fix this?