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

与显示对象的格式相同。


当前回答

var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);

其他回答

console.dir(对象):

显示指定JavaScript对象的财产的交互式列表。此列表允许您使用公开三角形来检查子对象的内容。

请注意,console.dir()特性是非标准的。查看MDN Web文档

我需要一种递归打印对象的方法,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) ); 

我总是使用console.log(“对象将是:”,obj,obj1)。这样我就不需要用JSON来解决字符串问题。对象的所有财产都将很好地展开。

简单使用

JSON.stringify(obj)

实例

var args_string = JSON.stringify(obj);
console.log(args_string);

Or

alert(args_string);

此外,注意javascript函数被视为对象。

作为补充说明:

实际上,您可以像这样分配新属性并访问它console.log或在警报中显示它

foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);

功能:

var print = function(o){
    var str='';

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

    return str;
}

用法:

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

$('body').append( print(myObject) );

例子:

http://jsfiddle.net/WilsonPage/6eqMn/