Node.js - console.log 不显示数组中的项目而是显示 \[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 中记录数组内容,即使它嵌入在内部并且对象位于外部对象中。

原文由 mikeym 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 547
1 个回答

这是某些浏览器和使用 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

原文由 Daniel Pérez 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题