繁体   English   中英

Node.js - console.log 不显示数组中的项目,而是显示 [Object]

[英]Node.js - console.log does not show items in array but instead shows [Object]

我在注销对象内的数组内容时遇到问题。 实际对象看起来像这样

   var stuff = { accepted: [ 'item1', 'item2' ],
         rejected: [],
         response: 'Foo',
         envelope: { from: 'The sender', to: ['new item1', 'new item2'] },
         messageId: 'xxxxxxxxxxxxx' } }

console.log显示第一个数组的项目很好,但第二个数组被输出为[Object]

 { accepted: [ 'item1', 'item2' ],
             rejected: [],
             response: 'Foo',
             envelope: { from: 'The sender', to: [Object] },
             messageId: 'xxxxxxxxxxxxx' } } 

这里发生了什么以及如何在我console.log时显示第二个数组的项目。 谢谢你的帮助!

更新

抱歉,我忘了补充一点,我只在 Node.js 中工作,因此它是一个服务器端日志,需要完全按照从带有直接console.log的回调接收到的对象来显示对象,即。 没有进一步的字符串化。

我也只是尝试创建另一个具有类似结构的随机对象。

 var objText = {
      fun: {
        stuff: 'Some stuff',
        list: ['this', 'it', 'takes']
      }
    };

上面的console.log是:

{ fun: { stuff: 'Some stuff', list: [ 'this', 'it', 'takes' ] } }

这对我来说似乎是相同的结构,但console.log工作正常,因此即使在 Node 中嵌入数组内容并将对象嵌入外部对象中,它似乎也完全有可能记录数组内容。

这是某些浏览器和使用 console.log 显示太复杂或太深的对象/数组的实现的默认方式。 另一种方法是将 JSON.stringify 与 console.log 一起使用:

 var stuff = { accepted: ['item1', 'item2'], rejected: [], response: 'Foo', envelope: { from: 'The sender', to: ['new item1', 'new item2'] }, messageId: 'xxxxxxxxxxxxx' } console.log(JSON.stringify(stuff, null, 4));

编辑:

另一种选择是使用console.dir以防您有一个太复杂或递归的对象,请参阅https://stackoverflow.com/a/27534731/6051261

反正这是个老话题了

我遇到了同样的问题,嵌入的数组打印为[Array]

因为 node.js 中的 console.log 使用util.inspect进行打印,默认深度为 2。 所以,打印比 2 深的东西可以使用:

const util = require('util')
console.log(util.inspect(errors, true, 10))

试试看: console.log(JSON.stringify(variable))

如果你喜欢 Chrome devtools,它会折叠你的 json 对象并让你观察很多事情,你可以使用--inspect标志:

node --inspect index.js

然后控制台会给你一个 URL,你只需要在谷歌浏览器中复制粘贴即可享受谷歌浏览器控制台。

有关此链接的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM