简体   繁体   中英

Making a table with arrays, and subarray, accessing and reassigning specific elements

a general question here, but something is not working right here, I have made a table of iterable points, using 6 arrays containing seven sub arrays each, that each individual array can be accessed with ax and y. Only problem, as depicted is when I update lets say board[0][2] It will update the entire column... even though specified,

I have compiled and sumarized the problem, and made a screenshot attached. Anyone have an idea of what might be going wrong here?

Here is my reproduced sample code

let height = 6;
let width = 6;

let board = []
let row = [];

for(let x = 0; x < width; x++){
  row.push([]);
}

for(let y = 0; y < height; y++){
  board.push(row)
}



board[1][5] = 1;



console.log(board)

//Output:

[
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ],
  [ [], [], [], [], [], 1 ]
]

I am trying only to update the 5th array element of the array 1

I was expecting that the individual subArray element to be changed, and I have tried many different ways to implement this.

maybe use Array.from method without referenced

let height = 6;
let width = 6;

let board = []

for(let y = 0; y < height; y++){
  board.push(Array.from({ length: width }, () => []))
}

board[1][5] = 1;

console.log(board)

board[0][0].push(2);

console.log(board)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM