在 Javascript 中,二维数组只是数组的数组。因此,克隆一维是不够的。我们还需要克隆所有的子维度数组。我们是这样做的:
function cloneGrid(grid) {
// Clone the 1st dimension (column)
const newGrid = [...grid]
// Clone each row
newGrid.forEach((row, rowIndex) => newGrid[rowIndex] = [...row])
return newGrid
}
// grid is a two-dimensional array
const grid = [[0,1],[1,2]]
newGrid = cloneGrid(grid)
console.log('The original grid', grid)
console.log('Clone of the grid', newGrid)
console.log('They refer to the same object?', grid === newGrid)
---
The original grid [ [ 0, 1 ], [ 1, 2 ] ]
Clone of the grid [ [ 0, 1 ], [ 1, 2 ] ]
They refer to the same object? false
或者如果我们利用ES6 Array.map操作,我们可以让cloneGrid
函数更简单:
const cloneGrid = (grid) => [...grid].map(row => [...row])
有关更多扩展答案,请阅读如何在 JavaScript 中制作数组的副本