Converting an object to a string

后端 未结 30 1851
北荒
北荒 2020-11-22 03:29

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:

30条回答
  •  清酒与你
    2020-11-22 04:16

    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

提交回复
热议问题