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

时间:2014-01-25 14:25:38

标签: 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中对此进行了测试。

3 个答案:

答案 0 :(得分:2)

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个不同的阵列。

答案 1 :(得分:0)

某些浏览器(特别是Chrome)具有console.log()的异步实现。您的代码修改了“getRandomMatrix()”函数中的“matrix_empty”数组。将数组传递给JavaScript中的函数时,将引用传递给数组,而不是副本。

正在发生的事情是,console.log()调用显示了该函数调用的结果,即使您的代码在创建之前调用了console.log()。 (编辑 - 我确实也看到了Firefox中的行为。)

答案 2 :(得分:0)

简短的回答是它在所有位置都显示-1,但是当您触发getRandomMatrix函数时,该值立即被更改。由于所有对象都是通过引用传递而不是通过值传递,因此数组会更改,但是您无法看到原始值。

如果你看看我用来显示这个变化的小提琴,你可以看到这种情况。

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

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

for (var x = 0; x < cols; x++) {
    matrix_empty[x] = [];
    for (var y = 0; y < rows; y++) {
        matrix_empty[x][y] = -1;
    }
}
console.clear(); // Just to empty the console so we don't confuse the results. 
console.log(matrix_empty); //here give me wrong result not -1 in whole position

setTimeout(function() { 
    matrix_test = getRandomMatrix(matrix_empty);
    console.log(matrix_empty);
}, 10000);

首先将延迟设置为10秒,这样您就有时间在调试器中打开数组并验证值确实都是-1。

但是,如果您等待setTimeOut函数在10秒后触发(或使超时更短),而不打开阵列,则在第二个阵列登录到控制台后,现在可以打开两个阵列并确认是的,他们都已被更改。另一种查看引用传递引用vs传递值的方法。

http://jsfiddle.net/vDgJ3/