如果我们对某个对象执行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}
答案 0 :(得分:2)
- 在浏览器中
因为当你使用console.log('Logging: ' + myThing)
时,它使用字符串连接,其中对象myThing
被转换为字符串表示[object Object]
您可以使用
console.log('Logging: ', myThing)
或使用JSON.stringify() - 在现代浏览器中(对于旧浏览器,使用像json2这样的库)
console.log('Logging: ' + JSON.stringify(myThing))
答案 1 :(得分:2)
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 }