当我将javascript对象添加到数组时,它们的属性会更改

时间:2019-12-18 01:03:56

标签: javascript arrays javascript-objects

我有这种类型的对象:

//This is a single cell
{
  state: 0,
  row: 0,
  col: 0
}

我想拥有:单元(列)的数组(板行)的数组(板状态)的数组,但是当我向板状态数组添加新行时,每列都更改为59,而没有原因(59列是最大可能的行,24列是最大的行)。

let board = this.cells //Actuall board
  let newBoards = []//Array of all the boards
  let cellNeighbors //Save the number of neighbors of x cell
  let rowOfCells = [] // An array whit a row of cells
  let newCell


    newBoards.push([])
    for(let i = 0; i < board.length; i++)
    {
      newCell = {state: 0, row: 0, col: 0} //A new cell to push into an array

      for(let j = 0; j < board[i].length; j++)
      {  
        newCell.row = i 
        newCell.col = j

        cellNeighbors = countNeighbors(i, j, board)

        // Apply rules to cell
        newCell.state = rulesAply(cellNeighbors, board[i][j].state)
        // Add new cells to an array
        rowOfCells.push(newCell)
        // Set timeout for make a steps animation of every state in the array
      }
      newBoards[0].push(rowOfCells)
      rowOfCells = []
    }
console.log(newBoards)

我的输出是这样的:

[Array(24)]
0: Array(24)
0: Array(60)
0: {state: 0, row: 0, col: 59}
1: {state: 0, row: 0, col: 59}
2: {state: 0, row: 0, col: 59}
3: {state: 0, row: 0, col: 59}
4: {state: 0, row: 0, col: 59}
5: {state: 0, row: 0, col: 59}
6: {state: 0, row: 0, col: 59}
7: {state: 0, row: 0, col: 59}
8: {state: 0, row: 0, col: 59}
9: {state: 0, row: 0, col: 59}
10: {state: 0, row: 0, col: 59}
11: {state: 0, row: 0, col: 59}
12: {state: 0, row: 0, col: 59}
13: {state: 0, row: 0, col: 59}
14: {state: 0, row: 0, col: 59}
15: {state: 0, row: 0, col: 59}
16: {state: 0, row: 0, col: 59}
17: {state: 0, row: 0, col: 59}
18: {state: 0, row: 0, col: 59}
19: {state: 0, row: 0, col: 59}
20: {state: 0, row: 0, col: 59}
21: {state: 0, row: 0, col: 59}
22: {state: 0, row: 0, col: 59}
23: {state: 0, row: 0, col: 59}
24: {state: 0, row: 0, col: 59}
25: {state: 0, row: 0, col: 59}
26: {state: 0, row: 0, col: 59}
27: {state: 0, row: 0, col: 59}
28: {state: 0, row: 0, col: 59}
29: {state: 0, row: 0, col: 59}

并继续每一行,每个col始终为59。

1 个答案:

答案 0 :(得分:1)

您仅在外循环中创建一个newCell,因此当您在内循环中.push时,您会将内存中的相同对象推送到数组中多次。而是在内循环内创建对象:

for (let i = 0; i < board.length; i++) {
  const rowOfCells = [];
  for (let j = 0; j < board[i].length; j++) {
    const newCell = { state: 0, row: i, col: j };
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    cellNeighbors = countNeighbors(i, j, board)

    // Apply rules to cell
    newCell.state = rulesAply(cellNeighbors, board[i][j].state)
    // Add new cells to an array
    rowOfCells.push(newCell)
    // Set timeout for make a steps animation of every state in the array
  }
  newBoards.push(rowOfCells);
}

(肯定要将新的单元格行推送到新的newBoards数组,而不是其第一个孩子)

或者,使用数组方法代替:

const newBoards = board.map((rowArr, row) => (
  row.map((oldCell, col) => (
    { row, col, state: countNeighbors(row, col, board) }
  ))
));