How do I display the content of a JavaScript object in a string format like when we alert
a variable?
(如何像alert
变量一样以字符串格式显示JavaScript对象的内容?)
The same formatted way I want to display an object.
(我想显示对象的格式相同。)
ask by maxjackie translate from so How do I display the content of a JavaScript object in a string format like when we alert
a variable?
(如何像alert
变量一样以字符串格式显示JavaScript对象的内容?)
The same formatted way I want to display an object.
(我想显示对象的格式相同。)
ask by maxjackie translate from so Use native JSON.stringify
method.
(使用本机JSON.stringify
方法。)
(与嵌套对象一起使用,并且所有主流浏览器都支持此方法。)
str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()
Link to Mozilla API Reference and other examples.
(链接到Mozilla API参考和其他示例。)
obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
Use a custom JSON.stringify replacer if you encounter this Javascript error
(如果遇到此Javascript错误,请使用自定义JSON.stringify替换程序)
"Uncaught TypeError: Converting circular structure to JSON"