Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm running this in node.js:

> x = { 'foo' : 'bar' }
{ foo: 'bar' }
> console.log(x)
{ foo: 'bar' }
undefined
> console.log("hmm: " + x)
hmm: [object Object]
undefined

What I don't understand is why console.log(x) "pretty-prints" the object, whereas string concatenation "ugly-prints" it. And more importantly, what's the best way to make it print hmm: { foo: 'bar' }?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
365 views
Welcome To Ask or Share your Answers For Others

1 Answer

The + x coerces the object x into a string, which is just [object Object]:

http://jsfiddle.net/Ze32g/

The pretty printing is a very nice and probably very complex underlying code that someone implemented as part of the console object and the log method.

Try this:

console.log("hmm: ", x);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...