I have a string that has been converted into an 2D Array in js.
board = "…|.X.|…|"
It is used to represent a game board
each . represents a space
each | represents a row
each X represents a wall
EDIT: code below for the 2d array creation
var src= "...|.X.|...|";
board = src.split(/\|/g);
for (var i = 0; i < board.length; i++) {
var cells = board[i].split('');
for (var j = 0; j < cells.length; j++) {
cells[j] = parseInt(cells[j]);
}
board[i][j] = cells;
console.log(board[1][1])
//returns 'X'
when i access board[i][j] it returns correctly:
[0][0] = "."
[1][1] = "X"
[1][2] = "."
etc etc
I want to update the specific element with a string representing a piece.
However when i insert into an element like so:
board[0][0] = "piece4"
The array returns in firebug as so:
board = "piece4|.X.|…|"
When it should look like:
board = ".piece4.|.X.|…|"
Why are elements [0][1] and [0][2] being overwritten? Am I not understanding arrays of array index access correctly in js?
PROBLEM:
I’m betting that you have a one-dimensional array with strings stored in each. So your array actually looks like:
When this is what you want:
SOLUTION:
When constructing your 2D array, make sure you explicitly declare each entry in
boardas an array. So to construct it, your code might look something like this: