javascript console.log 在变量中给出错误的结果

标签 javascript function variables matrix console.log

var cols = 9;
var rows = 9;
var matrix_empty = [];

for (var x = 0; x < cols; x++) {
    matrix_empty[x] = [];
    for (var y = 0; y < rows; y++) {
        matrix_empty[x][y] = -1;
    }
}
console.log(matrix_empty); //here give me wrong result not -1 in whole position

matrix_test = getRandomMatrix(matrix_empty);

function getRandomMatrix(matrix) {
    matrix[0][1] = 39;
    matrix[1][1] = 9;
    matrix[2][2] = 9;
    return matrix;
}

问题:

为什么控制台日志给我错误的结果? 他们给我:

matrix[0][1] =39;
matrix[1][1] = 9;
matrix[2][2] = 9;

但我希望整个矩阵为 -1!

我该怎么办,这在 console.log 的整个矩阵中给了我 -1(设置在这个位置)

我在 Firefox 和 Chrome 中对此进行了测试。

最佳答案

Chrome 不会像您使用 console.log 时那样保留对象的副本,它会使用引用并在您检查对象时对其求值。如果你想看到这个对象,就像你在 console.log 时看到的那样,你应该 JSON.stringify() 它是这样的: console.log(JSON.stringify(matrix_empty)) 顺便说一句,只是为了让您知道 matrix_empty 指向与 matrix_test 相同的对象,所以如果您更改 matrix_test,您将更改 matrix_empty。如果你想要 2 个不同的对象,我建议如下: var matrix = $.extend(true,[],matrix_empty);这样你就会有 2 个不同的数组。

关于javascript console.log 在变量中给出错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21351737/

相关文章:

php - 将 IF 条件放入变量中

c - 从方法中设置#define值

javascript - ValidationPipe() 不适用于 Nestjs/Crud 中的重写 @Query

javascript - PHP Javascript 图像渲染

javascript - 在 Express 中间件中提供自定义参数

重新排序对称小标题

javascript - 从字符串输入执行JS代码

python - Z3 中的变量消除

javascript - 为什么 Math.toString() 返回 [object Math]?

javascript - select2 bootstrap 大小问题