将depth参数添加到console.log以进行递归

时间:2011-05-03 23:32:30

标签: javascript jquery debugging recursion

我正在尝试调试一个递归函数,如果我能跟踪深度会很好。我试图编写一个版本的console.log,它带有一个深度参数,并在日志中添加了相应数量的空格,但它不能正常工作。最大的问题是当通过Chrome调试器运行时,jquery对象的显示方式不同。理想情况下,dlog函数与console.log相同,除了前置n个空格,其中n =深度* 2.

<!-- nested divs -->
<style>
  .node {margin-left:20px}
</style>

<div class = 'container'>
  <div class='node'><span class='text'>1</span>
    <div class='node'><span class='text'>2</span>
      <div class='node'><span class='text'>3</span>
      </div>
    </div>
  </div>
</div>

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script>
<script>

// Log with depth
function dlog() {
  var depth = arguments[arguments.length - 1]
  var real_args = []
  for(var i = 0; i < arguments.length - 1; i++)
    real_args.push(arguments[i])
  var ds = ''
  for(var i = 0; i < depth; i++) ds += '  '
  console.log(ds, real_args)
}

// Just walk through the node tree, logging as we go.
function walk_node(node, depth) {
  dlog('walking node: ', node, depth)
  console.log('walking node: ', node)
  var child = node.children('.node').first()
  if(child.length > 0)  walk_node(child, depth + 1)
}

walk_node($('.container'), 0)
</script>

2 个答案:

答案 0 :(得分:2)

我在Java和C中实现了非常相似的功能,方法是将前缀字符串传递给日志记录函数,并在每个递归级别将空格附加到前缀字符串。每次要打印时,构造前缀字符串可能比循环更有效。

所以你可能会有更好的运气:

// Log with depth
function dlog() {
  var depth = arguments[arguments.length - 1];
  var real_args = [];
  real_args.push(prefix);
  for(var i = 0; i < arguments.length - 1; i++)
    real_args.push(arguments[i]);
  console.log.apply(console, real_args);
}

// Just walk through the node tree, logging as we go.
function walk_node(node, prefix) {
  if (! prefix) {
    prefix = '';
  }
  dlog('walking node: ', node, prefix);
  console.log('walking node: ', node);
  var child = node.children('.node').first();
  if(child.length > 0)  walk_node(child, prefix + ' ');
}

答案 1 :(得分:1)

我认为问题是你的for循环将节点分成多个部分。如果你没有能够向dlog()发送可变数量的参数的灵活性,那么将dlog()更改为this应该可以解决你的问题:

// Log with depth
function dlog() {
  var depth = arguments[2]
  var label = arguments[0];
  var real_args = arguments[1]
  var ds = ''
  for(var i = 0; i < depth; i++) ds += '  '
  console.log(label+ds, real_args)
}

显然,该代码还有改进的余地(例如上述发送可变数量参数的能力,或至少一些错误检查,以确保已发送正确数量的参数,并且它们是正确的类型)。但是如果你只是想做一些快速和脏的调试,并希望输出与其他console.log()调用相同,那应该这样做......