Converting an object to a string

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

    EDIT Do not use this answer as it works only in some versions of Firefox. No other browsers support it. Use Gary Chambers solution.

    toSource() is the function you are looking for which will write it out as JSON.

    var object = {};
    object.first = "test";
    object.second = "test2";
    alert(object.toSource());
    

提交回复
热议问题