![](/img/trans.png)
[英]Javascript objects in array of objects,are different using console.log
[英]Different behavior when printing Javascript Objects in console.log
如果我们对对象进行console.log()
,我们将看到其属性。 但是,如果console.log
包含其他字符串,则仅获得[object Object]
问题:为什么它不打印出对象的属性? 我们如何使用console.log
来打印出我们的字符串和对象的属性? 如果有帮助,可以使用Underscore.js和节点包。
> myThing = {'name': 'Doge', 'value': 1000}
Object {name: "Doge", value: 1000}
> console.log(myThing)
Object {name: "Doge", value: 1000}
> console.log('Logging: ' + myThing)
Logging: [object Object]
期望的输出
Logging: Object {name: "Doge", value: 1000}
-在浏览器中
因为当您使用console.log('Logging: ' + myThing)
它使用字符串连接,其中将对象myThing
转换为字符串表示形式[object Object]
您可以使用
console.log('Logging: ', myThing)
或使用JSON.stringify() -在现代浏览器中(对于旧的浏览器,请使用json2之类的库)
console.log('Logging: ' + JSON.stringify(myThing))
Node.js具有一个名为util
的内置模块,您可以使用util.inspect
显示对象。
var util = require("util");
myThing = {'name': 'Doge', 'value': 1000};
console.log(myThing);
console.log('Logging: ' + myThing);
console.log('Logging: ' + util.inspect(myThing));
产量
{ name: 'Doge', value: 1000 }
Logging: [object Object]
Logging: { name: 'Doge', value: 1000 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.