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

与显示对象的格式相同。


当前回答

你可以使用我的功能。使用数组或字符串或对象调用此函数,以提醒内容。

作用

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

用法

var data = [1, 2, 3, 4];
print_r(data);

其他回答

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

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

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;
};

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

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

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

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

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

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

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

在ES2015中,使用对象文本的速记属性声明语法,您可以记录对象,同时也可以简洁地保留变量名:

console.log("bwib:", bwib, "bwab:", bwab, "bwob": bwob) // old way A
console.log({bwib: bwib, bwab: bwab, bwob: bwob})       // old way B

console.log({bwib, bwab, bwob})                         // ES2015+ way