Why console.log displays incorrect object's values?

北城以北 提交于 2019-12-11 03:54:23

问题


I don't understand why console.log displays that d1 contains [100,200,300] before I even introduced these numbers. Regular for loop displays internals of d1 correctly though. Can someone please explain this behavior/bug of console.log in Google Chrome? https://jsfiddle.net/ZSvyt/

var container = {};
container["0"] = [10, 20, 30];
var d1 = container;

console.log('before console.log');
console.log(d1); // <--- IT DISPLAYS [100, 200, 300]. WHY?

// before for loop
console.log('before for loop');
for (var i = 0; i < d1["0"].length; i++) {
    console.log(d1["0"][i]);
}

container["0"] = [100, 200, 300];

console.log('after console.log');
console.log(d1);

// after for loop
console.log('after for loop');
for (var i = 0; i < d1["0"].length; i++) {
    console.log(d1["0"][i]);
}

Output:

before console.log
Object {
    0: Array[3]
}
0: Array[3] 
0: 100
1: 200
2: 300 

before for loop
10
20
30

after console.log
Object {
    0: Array[3]
}
0: Array[3] 
0: 100
1: 200
2: 300

after for loop
100
200
300

回答1:


that's because what is in the console is the reference of dt not a copy.

you can copy the object and log it (the code from this question ).

or you can log the string that represents it using JSON.stringify.

console.log( JSON.stringify(dt) ); will print it as string.



来源:https://stackoverflow.com/questions/30150469/why-console-log-displays-incorrect-objects-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!