在 JavaScript 中推送到另一个数组时,数组返回起始值 [duplicate]

Array returns to starting values when pushed into another array in JavaScript [duplicate]

提问人:Luis Belloch 提问时间:10/28/2023 更新时间:10/28/2023 访问量:37

问:

我有这个简单的递归

function solve(matrix, pieces) {
    // Get next -1
    let nextEmpty = getNextEmtpy(matrix);
    if (!nextEmpty) {
        console.log(matrix)
        solutions.push(matrix);
    }
    let row = nextEmpty.row;
    let col = nextEmpty.col;
    // Try all pieces that are not in the matrix
    for (let i = 1; i < pieces.length; i++) {
        if (matrix.flat().includes(i)) continue;
        for (let r = 0; r < 4; r++) {
            let fit = rotatePiece(pieces[i]);
            if (col == 0) {
                if (fit[0] != 0) continue;
            }
            if (row == 0) {
                if (fit[1] != 0) continue;
            }
            if (col == matrix[0].length - 1) {
                if (fit[2] != 0) continue;
            }
            if (row == matrix.length - 1) {
                if (fit[3] != 0) continue;
            }
            // If the piece is not in a border
            if (col > 0) {
                if (fit[0] != pieces[matrix[row][col - 1]][2]) continue;
            }
            if (row > 0) {
                if (fit[1] != pieces[matrix[row - 1][col]][3]) continue;
            }
            // Add the piece to the matrix
            matrix[row][col] = i;
            // Update pieces
            pieces[i] = fit;
            // Recurse
            let solution = solve(matrix, pieces);
            // Reset the value 
            matrix[row][col] = -1;
        }
    }
    return false;
}

它应该打印相同的值并将其添加到变量解决方案中。但是,它可以正确打印:

[
  [ 25, 1, 17, 24, 7 ],
  [ 19, 16, 23, 8, 15 ],
  [ 12, 14, 4, 2, 21 ],
  [ 5, 9, 11, 6, 18 ],
  [ 10, 13, 22, 20, 3 ]
]

但是当将这个矩阵添加到解决方案中时,即 [],它添加了:

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

这是矩阵的起始值。 ¿为什么会发生这种情况?

JavaScript 数组变量 递归

评论

1赞 David 10/28/2023
我不清楚你的意思。您能否将代码更新为一个可运行的最小可重现示例,该示例演示了问题,以便我们也可以观察它?此外,这是您开始熟悉调试器使用的好机会。在调试器中单步执行代码时,哪个操作首先会产生意外结果?该操作中使用的值是什么?结果如何?预期的结果是什么?为什么?
1赞 Tim Roberts 10/28/2023
您没有存储矩阵的 COPY。您的程序中正好有一个 5x5 矩阵,您只是保存了对该矩阵的多个引用。当程序结束时,该矩阵包含所有 -1。您需要研究如何克隆矩阵。
0赞 Luis Belloch 10/28/2023
感谢大卫的提示和蒂姆,这是一个记忆问题。矩阵已更改,但是当它推送到数组中时,它不会复制当前值,而是复制原始值。创建副本确实解决了这个问题。
0赞 VLAZ 10/28/2023
复制:为什么在 JavaScript 中更改数组会影响数组的副本? |如何在 JavaScript 中克隆对象数组?
0赞 VLAZ 10/28/2023
相关新闻: 按值复制数组

答:

-1赞 Luis Belloch 10/28/2023 #1

正如评论中所说,解决方案实际上是将矩阵复制到解决方案中,而不是直接引用它。

    if (!nextEmpty) {
    let copy = matrix.map((row) => row.slice());
    solutions.push(copy);
}