如何以字符串格式显示JavaScript对象的内容,就像我们警告变量时一样?

与显示对象的格式相同。


当前回答

在NodeJS中,您可以使用util.inspect(obj)打印对象。请务必说明深度,否则只能打印出对象的浅层。

其他回答

pagewils代码的另一个修改。。。他不打印字符串以外的任何内容,并将数字和布尔字段留空,我修复了megaboss创建的函数内部第二种类型的拼写错误。

var print = function( o, maxLevel, level )
{
    if ( typeof level == "undefined" )
    {
        level = 0;
    }
    if ( typeof maxlevel == "undefined" )
    {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 )
    {
        str = '<pre>';   // can also be <pre>
    }

    var levelStr = '<br>';
    for ( var x = 0; x < level; x++ )
    {
        levelStr += '    ';   // all those spaces only work with <pre>
    }

    if ( maxLevel != 0 && level >= maxLevel )
    {
        str += levelStr + '...<br>';
        return str;
    }

    for ( var p in o )
    {
        switch(typeof o[p])
        {
          case 'string':
          case 'number':    // .tostring() gets automatically applied
          case 'boolean':   // ditto
            str += levelStr + p + ': ' + o[p] + ' <br>';
            break;

          case 'object':    // this is where we become recursive
          default:
            str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
            break;
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 )
    {
        str += '</pre>';   // also can be </pre>
    }
    return str;
};

如果希望以表格格式查看数据,可以使用:

console.table(obj);

如果单击表列,可以对表进行排序。

您还可以选择要显示的列:

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

您可以在此处找到有关console.table的更多信息

如果要打印对象的全长,可以使用

console.log(require('util').inspect(obj,{showHidden:false,depth:null})

如果要通过将对象转换为字符串来打印该对象,则

console.log(JSON.stringify(obj));

这是函数。

function printObj(obj) {
console.log((function traverse(tab, obj) {
    let str = "";
    if(typeof obj !== 'object') {
        return obj + ',';
    }
    if(Array.isArray(obj)) {            
        return '[' + obj.map(o=>JSON.stringify(o)).join(',') + ']' + ',';
    }
    str = str + '{\n';
    for(var p in obj) {
        str = str + tab + ' ' + p + ' : ' + traverse(tab+' ', obj[p]) +'\n';
    }
    str = str.slice(0,-2) + str.slice(-1);                
    str = str + tab + '},';
    return str;
}('',obj).slice(0,-1)))};

它可以使用具有可读性的制表符缩进来显示对象。

试试看:

console.log(JSON.stringify(obj))

这将打印对象的字符串版本。因此,您将获得object的内容,而不是[object]作为输出。