节点console.log/util.inspect嵌套对象/数组 [英] node console.log / util.inspect for nested Object / Array

查看:66
本文介绍了节点console.log/util.inspect嵌套对象/数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于嵌套对象或数组

var obj = {
  foo:
  {
    foo:
    {
      foo:
      {
        foo:
        {
          foo:
          {
            foo: 'foo'
          }
        }
      }
    }
  }
};
console.log(obj);
util.debug(obj);
util.debug(util.inspect(obj));

console.log util.debug + util.inspect

{ foo: { foo: { foo: [Object] } } }
DEBUG: [object Object]
DEBUG: { foo: { foo: { foo: [Object] } } }

在一定深度下,它仅显示 [Object] ,没有进一步的细节.

Under a certain depth, it shows just [Object] with no further detail.

由于我无法调查实际值,因此调试总是很烦人.

This is always annoying on debugging since I can't investigate the actual value.

为什么 node (或V8)为什么这样实现?并且有任何解决方法吗?

Why does node (or V8) implements like this? and Is there any work-around?

谢谢.

我收到了一个建议

console.log(JSON.stringify(obj));

结果

{"foo":{"foo":{"foo":{"foo":{"foo":{"foo":"foo"}}}}}}

这是可行的,但显然整个过程都是 stringify 的,并且在调试时我可能无法对所有对象输出执行此操作.不是通用方法.

It sort of works, but obviously the whole is stringifyed, and probably I couldn't do this for all object output on debugging. Not generic method.

解决方案:

console.log(util.inspect(obj,{depth:null}));

输出:

{foo:{foo:{foo:{foo:{foo:{foo:'foo'}}}}}}}

酷.这就是我想要的!

推荐答案

util.inspect()使用第二个 options 参数,您可以在其中指定 depth.默认值为2.

util.inspect() takes a second options argument, where you can specify depth. The default is 2.

http://nodejs.org/api/util.html#util_util_inspect_object_options

所以:

util = require('util');
var obj = { foo: { foo: { foo: { foo: { foo: { foo: 'foo' } } } } } };
console.log(util.inspect(obj, {depth:12}));

...产量:

{ foo: { foo: { foo: { foo: { foo: { foo: 'foo' } } } } } }

这篇关于节点console.log/util.inspect嵌套对象/数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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