Node.js - console.log 不显示数组中的项目,而是显示 [Object] [英] Node.js - console.log does not show items in array but instead shows [Object]

查看:53
本文介绍了Node.js - console.log 不显示数组中的项目,而是显示 [Object]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem with logging out the contents of an array inside an object. The actual object looks like this

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

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

The console.log shows the items of the first array fine but the second array is being output as [Object].

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

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

What is happening here and how can I get the items of the second array to show when I console.log. Thanks for any help!

更新

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

Sorry, I forgot to add that I am working exclusively in Node.js so it's a server side log that needs to display the object exactly as it's received from a callback with a straight console.log, ie. no further stringify-ing.

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

I also just tried creating another random object with a similar structure like this.

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

上面的console.log是:

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

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

This appears to be the same structure to me and yet the console.log works fine so it seems to be perfectly possible in Node to log arrays content even when it's embedded inside and an object inside an outer object.

推荐答案

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

This is the default way for some browser and implementations of showing too complex or deep objects/arrays with console.log. An alternative is to use JSON.stringify with 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

Another alternative is to use console.dir in case you have a too complex or recursive object, see https://stackoverflow.com/a/27534731/6051261

这篇关于Node.js - console.log 不显示数组中的项目,而是显示 [Object]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆