Recently delving into the realm of JavaScript programming, I find myself faced with a new challenge. While not my first language, this is one of my initial ventures with it. My current project involves creating a chess program utilizing the HTML5 canvas feature. To achieve this, I am using a for loop to generate an array containing all the positions for the chess pieces. However, I have encountered an issue where these coordinates are being stored as undefined. Below are the functions responsible for storing 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;
Below you will find the Position class required for reference.
class Position {
constructor(x, y) {
this.x = x;
this.y = y;
this.piece = null;
}
}
Upon executing createBoard(), attempting to utilize getPosition() throws errors related to handling null values. Reviewing the console output reveals a continual stream of "(undefined,undefined)." Despite research efforts pointing towards asynchronous issues, resolving them has proven elusive. Could someone provide guidance on remedying this situation?