Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - 如何显示JavaScript对象?(How can I display a JavaScript object?)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use native JSON.stringify method.

(使用本机JSON.stringify方法。)

Works with nested objects and all major browsers support this method.

(与嵌套对象一起使用,并且所有主流浏览器都支持此方法。)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...