Converting an object to a string

2018-12-31 17:03发布

How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)

Output:

Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(

30条回答
不流泪的眼
2楼-- · 2018-12-31 17:41

Keeping it simple with console, you can just use a comma instead of a +. The + will try to convert the object into a string, whereas the comma will display it separately in the console.

Example:

var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o);   // :)

Output:

Object { a=1, b=2}           // useful
Item: [object Object]        // not useful
Item:  Object {a: 1, b: 2}   // Best of both worlds! :)

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Console.log

查看更多
爱死公子算了
3楼-- · 2018-12-31 17:42

If you want a minimalist method of converting a variable to a string for an inline expression type situation, ''+variablename is the best I have golfed.

If 'variablename' is an object and you use the empty string concatenation operation, it will give the annoying [object Object], in which case you probably want Gary C.'s enormously upvoted JSON.stringify answer to the posted question, which you can read about on Mozilla's Developer Network at the link in that answer at the top.

查看更多
公子世无双
4楼-- · 2018-12-31 17:43

One option:

console.log('Item: ' + JSON.stringify(o));

o is printed as a string

Another option (as soktinpk pointed out in the comments), and better for console debugging IMO:

console.log('Item: ', o);

o is printed as an object, which you could drill down if you had more fields

查看更多
忆尘夕之涩
5楼-- · 2018-12-31 17:43

If you're just outputting to the console, you can use console.log('string:', obj). Notice the comma.

查看更多
心情的温度
6楼-- · 2018-12-31 17:43

In cases where you know the object is just a Boolean, Date, String, number etc... The javascript String() function works just fine. I recently found this useful in dealing with values coming from jquery's $.each function.

For example the following would convert all items in "value" to a string:

$.each(this, function (name, value) {
  alert(String(value));
});

More details here:

http://www.w3schools.com/jsref/jsref_string.asp

查看更多
宁负流年不负卿
7楼-- · 2018-12-31 17:43

For your example, I think console.log("Item:",o) would be easiest. But, console.log("Item:" + o.toString) would also work.

Using method number one uses a nice dropdown in the console, so a long object would work nicely.

查看更多
登录 后发表回答