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?

The same formatted way I want to display an object.


With Firefox

If you want to print the object for debugging purposes, I suggest instead installing Firebug for Firefox and using the code:

console.log(obj)

With Chrome

var obj = {prop1: 'prop1Value', prop2: 'prop2Value', child: {childProp1: 'childProp1Value'}}
console.log(obj)

will display

截图控制台铬

Note : you must only log the object. For exemple this won't work :

console.log('My object : ' + obj)

Use native JSON.stringify method. 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.

obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

Use a custom JSON.stringify replacer if you encounter this Javascript error

"Uncaught TypeError: Converting circular structure to JSON"

var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);
链接地址: http://www.djcxy.com/p/4700.html

上一篇: 当用户悬停在列表项上时,如何让光标成为一只手?

下一篇: 我怎样才能显示一个JavaScript对象?