[英]Different behavior when printing Javascript Objects in console.log
If we do a console.log()
of an object, we see its attributes. 如果我们对对象进行
console.log()
,我们将看到其属性。 However if the console.log
includes other strings, we get only [object Object]
但是,如果
console.log
包含其他字符串,则仅获得[object Object]
Question: Why does it not print out the object's attributes? 问题:为什么它不打印出对象的属性? How can we use
console.log
to print out both our string and the object's attributes? 我们如何使用
console.log
来打印出我们的字符串和对象的属性? Underscore.js and node packages can be used if they help. 如果有帮助,可以使用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]
Desired Output 期望的输出
Logging: Object {name: "Doge", value: 1000}
--In browser -在浏览器中
because when you use console.log('Logging: ' + myThing)
it uses string concatenation where the object myThing
is converted to string representation [object Object]
因为当您使用
console.log('Logging: ' + myThing)
它使用字符串连接,其中将对象myThing
转换为字符串表示形式[object Object]
You can use 您可以使用
console.log('Logging: ', myThing)
or use JSON.stringify() - in modern browsers(for old browsers use a library like json2 ) 或使用JSON.stringify() -在现代浏览器中(对于旧的浏览器,请使用json2之类的库)
console.log('Logging: ' + JSON.stringify(myThing))
Node.js has a built-in module called, util
and you can use util.inspect
to display the Object. 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));
Output 产量
{ name: 'Doge', value: 1000 }
Logging: [object Object]
Logging: { name: 'Doge', value: 1000 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.