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

与显示对象的格式相同。


当前回答

正如之前所说,我发现的最简单的方法是

var getPrintObject=function(object)
{
    return JSON.stringify(object);
}

其他回答

我需要一种递归打印对象的方法,pagewil提供了答案(谢谢!)。我对它进行了一点更新,以包括一种打印到某个级别的方法,并添加间距,以便根据当前级别正确缩进,以便更易于阅读。

// Recursive print of object
var print = function( o, maxLevel, level ) {
    if ( typeof level == "undefined" ) {
        level = 0;
    }
    if ( typeof level == "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>';
    }

    var levelStr = '';
    for ( var x = 0; x < level; x++ ) {
        levelStr += '    ';
    }

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

    for ( var p in o ) {
        if ( typeof o[p] == 'string' ) {
            str += levelStr +
                p + ': ' + o[p] + ' </br>';
        } else {
            str += levelStr +
                p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
        }
    }

    // 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>';
    }
    return str;
};

用法:

var pagewilsObject = {
    name: 'Wilson Page',
    contact: {
        email: 'wilson@hotmail.com',
        tel: '123456789'
    }  
}

// Recursive of whole object
$('body').append( print(pagewilsObject) ); 

// Recursive of myObject up to 1 level, will only show name 
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) ); 
var list = function(object) {
   for(var key in object) {
     console.log(key);
   }
}

其中object是您的对象

或者您可以在chrome开发工具的“控制台”选项卡中使用此选项:

console.log(对象);

显示对象内容的一种简单方法是使用console.log,如下所示

console.log("Object contents are ", obj);

请注意,我没有使用“+”连接对象。如果我使用“+”,那么我将只得到If对象的字符串表示,类似于[Objectobject]。

我更喜欢使用console.table来获得清晰的对象格式,所以假设您有这个对象:

const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};

您将看到一张整洁易读的表格,如下所示:

您还可以使用ES6模板文本概念以字符串格式显示JavaScript对象的内容。

alert(`${JSON.stringify(obj)}`);

常量对象={“name”:“John Doe”,“habbits”:“没有”,};警报(`${JSON.stringify(obj)}`);