How can I create the starting positon on a coordinate plot and update (increment) the x value? Initially, position
was given values of 2
and 5
, but for testing purposes, I'd just like to update the x value by 1, but am getting the same values returned?
function boardCreate(rows, columns) {
for (let x = 0; x < rows; x++) {
for (let y = 0; y < columns; y++) {
boardCell(x, y);
}
}
}
function boardCell(x, y) {
board[x] = board[x] || [];
board[x][y] = x + " " + y;
}
var board = [];
boardCreate(10, 10);
let position = board[2][5];
function incrementX(position) {
position[1] = position[1] + 1;
return position;
}
incrementX(position);
console.log(position);
If I understand correctly, you need to increment the board coordinates based on the x
and y
values of the current position
- this can be achieved by:
extracting the x
and y
values at the specified position
const [x, y] = position.split(' ');
incrementing x
by one:
const nextX = Number.parseInt(x) + 1;
reading the new position value from new x
value and exisiting y
return board[nextX][y]
Hope this helps!
function boardCreate(rows, columns) { for (let x = 0; x < rows; x++) { for (let y = 0; y < columns; y++) { boardCell(x, y); } } } function boardCell(x, y) { board[x] = board[x] || []; board[x][y] = x + " " + y; } var board = []; boardCreate(10, 10); let position = board[2][5]; function incrementX(position) { /* Ensure valid position specified before attempting increment */ if (!position) { return; } /* Read x,y coordinates from array value */ const [x, y] = position.split(' '); /* Parse x to number and increment it */ const nextX = Number.parseInt(x) + 1; if (nextX >= board.length) { console.error(`next x: ${ nextX } out of bounds`); return; } /* Look up board value at next x, and same y coordinate */ return board[nextX][y] } console.log(position); /* Testing */ let p = incrementX(position); for (let i = 0; i < 10; i++) { p = incrementX(p); console.log(p); }
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.