Converting an object to a string

后端 未结 30 1866
北荒
北荒 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:26

    1.

    JSON.stringify(o);
    

    Item: {"a":"1", "b":"2"}

    2.

    var o = {a:1, b:2};
    var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
    b="{"+b.join(', ')+"}";
    console.log('Item: ' + b);
    

    Item: {a:1, b:2}

提交回复
热议问题