If we do a console.log()
of an object, we see its attributes. However if the console.log
includes other strings, we get only [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? Underscore.js and node packages can be used if they help.
> 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]
You can use
console.log('Logging: ', myThing)
or use JSON.stringify() - in modern browsers(for old browsers use a library like 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.
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 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.