How can I display a JavaScript object?

2018-12-31 03:25发布

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.

30条回答
公子世无双
2楼-- · 2018-12-31 03:35

try this :

console.log(JSON.stringify(obj))

This will print the stringify version of object. So instead of [object] as an output you will get the content of object.

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 03:35

Well, Firefox (thanks to @Bojangles for detailed information) has Object.toSource() method which prints objects as JSON and function(){}.

That's enough for most debugging purposes, I guess.

查看更多
临风纵饮
4楼-- · 2018-12-31 03:36
var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);
查看更多
只若初见
5楼-- · 2018-12-31 03:36

If you would like to see data in tabular format you can use

console.table(obj);

Table can be sorted if you click on the table column.

You can also select what columns to show:

console.table(obj, ['firstName', 'lastName']);

You can find more information about console.table here

查看更多
皆成旧梦
6楼-- · 2018-12-31 03:40

console.dir(object):

Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.

Note that the console.dir() feature is non-standard. See MDN Web Docs

查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 03:40

i used pagewil's print method, and it worked very nicely.

here is my slightly extended version with (sloppy) indents and distinct prop/ob delimiters:

var print = function(obj, delp, delo, ind){
    delp = delp!=null ? delp : "\t"; // property delimeter
    delo = delo!=null ? delo : "\n"; // object delimeter
    ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
    var str='';

    for(var prop in obj){
        if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
          var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
          str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
        }else{
          str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
        }
    }
    return str;
};
查看更多
登录 后发表回答