Javascript控制台日志报告对象属性不正确 [英] Javascript Console Log reporting object properties incorrectly
问题描述
这可能是JS Fiddle的问题,但我使用 console.log()
来打印对象集合的值。
This could be a problem with JS Fiddle, but I am using console.log()
to print the values of a collection of objects.
首先我用一些数据(一些对象)初始化对象集合,然后控制台记录它。
First I initialize the object collection with some data (some objects) and console log it.
然后我用一些新的更新这个集合数据和控制台记录它。
Then I update this collection with some new data and console log it.
正在发生的事情是第一个和第二个控制台日志都是相同的,即使对象数据已更改。我想知道这是一个错误,还是我做错了什么。
What is happening is that the first and second console logs are both identical, even though the object data was changed. I would like to know if this is a bug, or if I am doing something wrong.
http://jsfiddle.net/n302nsbh/18/
function FooManager() {
this.objects = {};
this.update = function(data) {
var self = this;
$.each(data, function(i, e) {
var foo = self.objects[i];
if (typeof foo === "undefined") {
foo = new Foo(e);
self.objects[i] = foo;
} else if (foo instanceof Foo) {
foo.update(e);
}
});
}
return this;
}
function Foo(data) {
this.name = data.name;
this.age = data.age;
return this;
}
Foo.prototype.update = function(data) {
this.name = data.name;
this.age = data.age;
}
//------ Update 1 --------//
var appData = {
"0": {
name: "a",
age: 2
},
"1": {
name: "b",
age: 3
}
}
var fooManager = new FooManager();
fooManager.update(appData);
console.log(fooManager.objects);
//------ Update 2 --------//
var newAppData = {
"0": {
name: "a",
age: 443
}
}
fooManager.update(newAppData);
console.log(fooManager.objects);
更新1和更新2日志都是相同的!
Both update 1 and update 2 logs are identical!
推荐答案
当您调用 console.log()
时,浏览器不会保存整个对象,只是对它的引用。当您稍后检查它时,浏览器将获得该对象的当前版本。
The browser doesn't save the whole object when you call console.log()
, just a reference to it. When you inspect it later, the browser will get the current version of the object.
您可以通过向对象附加新元素来非常简单地测试它。
You can test this quite simple by appending a new element to the object.
最后调用:
var newAppData = {
"2": {
name: "a",
age: 443
}
}
在控制台中,它将显示为
In the console it'll show up as
Object {0: Foo, 1: Foo}
Object {0: Foo, 1: Foo, 2: Foo}
但是当您打开第一个日志条目时,您将看到所有三个元素,因此浏览器会检查当前版本。
but when you open the first log entry, you will see all three elements, so the browser inspects the current version.
演示: https://jsfiddle.net/n302nsbh/22/
解决方案1
要查看对象元素的当前版本,请直接使用 console.log(fooManager)引用它.objects [0]);
这将输出你的脚本:
To see the current version of an element of the object, directly refer to it with console.log(fooManager.objects[0]);
This will output for your script:
Foo {name: "a", age: 2}
Foo {name: "a", age: 443}
演示: https://jsfiddle.net/n302nsbh/23/
解决方案2
在 https://stackoverflow.com/a上找到了另一个不错的解决方案/ 7389177/1682509
使用 console.log(JSON.parse(JSON.stringify(fooManager.objects)));
获得可浏览的快照。
Use console.log(JSON.parse(JSON.stringify(fooManager.objects)));
to get a browsable snapshot.
演示: https://jsfiddle.net/n302nsbh/24/
这篇关于Javascript控制台日志报告对象属性不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!