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

与显示对象的格式相同。


当前回答

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

其他回答

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.log('print object: ' + JSON.stringify(session));

好吧,Firefox(感谢@Bojangles提供详细信息)有Object.toSource()方法,它将对象打印为JSON和function(){}。

我想,对于大多数调试目的来说,这已经足够了。

功能:

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/

试试这个:

var object = this.window;
console.log(object,'this is window object');

输出: