【问题标题】:Node.js - console.log does not show items in array but instead shows [Object]Node.js - console.log 不显示数组中的项目,而是显示 [Object]
【发布时间】:2017-11-10 16:37:53
【问题描述】:

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

   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 中记录数组内容,即使它嵌入在内部对象和外部对象内部。

【问题讨论】:

  • 您使用的是哪个浏览器/环境?在 Safari 10.1.1 中显示正常。
  • 比如nodejs就是这样记录的

标签: javascript arrays node.js object console.log


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果你喜欢 Chrome 开发工具,它可以折叠你的 json 对象并让你观察很多东西,你可以使用 --inspect 标志:

      node --inspect index.js
      

      然后控制台会为您提供一个 URL,您只需在 Google Chrome 中复制粘贴即可享受 Google Chrome 控制台。

      More information on this link

      【讨论】:

      • 感谢您的建议,但我在 Node 0.12 上,目前无法升级。
      【解决方案4】:

      看来这是个老话题了,反正

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

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

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

      【讨论】:

      • 这应该是公认的答案:1. console.log 确实使用深度 = 2 的 util.inspect(因此是 OP 的问题),以及 2. 使用建议的解决方案确实可以解决问题。此外,如果您将最后一个参数添加到 util.inspect 并传递 trueconsole.log 的行为将与之前相同(例如,也显示颜色)。深度(此处为 10)可以相应调整。
      猜你喜欢
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 2014-08-27
      • 2021-07-15
      相关资源
      最近更新 更多