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

与显示对象的格式相同。


当前回答

它在浏览器中不起作用,您可能只需要在您希望获得对象的有效JS表示而不是JSON的情况下使用它。它只运行节点内联求值

var execSync = require('child_process').execSync

const objectToSource = (obj) =>
  execSync('node -e \'console.log(JSON.parse(`' + JSON.stringify(obj) + '`))\'', { encoding: 'utf8' })

console.log(objectToSource({ a: 1 }))

其他回答

编号:在这些示例中,yourObj定义了要检查的对象。

首先,我最不喜欢但最常用的显示对象的方式:

这是显示对象内容的实际方式

console.log(yourObj)

将产生如下结果:

我认为最好的解决方案是查看对象关键点,然后查看对象值,如果您真的想查看对象的内容。。。

console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));

它将输出如下内容:(上图:存储在对象中的键/值)

如果您使用的是ECMAScript 2016或更高版本,还有一个新选项:

Object.keys(yourObj).forEach(e => console.log(`key=${e}  value=${yourObj[e]}`));

这将产生整洁的输出:前面的回答中提到的解决方案:console.log(yourObj)显示了太多的参数,并且不是显示所需数据的最方便用户的方式。这就是为什么我建议分别记录键和值。

下一步:

console.table(yourObj)

有人在之前的评论中建议过这个,但它从来没有对我起过作用。如果它对其他人在不同的浏览器或其他东西上起作用,那就太好了!我仍将代码放在此处以供参考!将向控制台输出如下内容:

如果您正在寻找可以返回任何javascript对象的美化字符串的东西,请查看https://github.com/fresheneesz/beautinator . 例如:

var result = beautinator({ "font-size": "26px","font-family": "'Open Sans', sans-serif",color: "white", overflow: "hidden",padding: "4px 4px 4px 8px",Text: { display: "block", width: "100%","text-align": "center", "padding-left": "2px","word-break": "break-word"}})
console.log(result)

结果如下:

{ "font-size": "26px",
  "font-family": "'Open Sans', sans-serif",
  color: "white", overflow: "hidden",
  padding: "4px 4px 4px 8px",
  Text: { display: "block", width: "100%",
          "text-align": "center", "padding-left": "2px",
          "word-break": "break-word"
  }
}

如果对象中有函数,它甚至可以工作。

console.log()在调试对象方面做得很好,但如果您希望将对象打印到页面内容中,这里是我提出的模仿PHP print_r()功能的最简单方法。很多其他答案都想重新发明轮子,但在JavaScript的JSON.stringify()和HTML的<pre>标记之间,你可以得到你想要的东西。

var obj={name:'名称',联系人:{email:'thename@gmail.com',电话:'123456789'};$('body').append('<pre>'+JSON.stringify(obj,null,4)+'</pre>');<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script>

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

作用

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

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