在console.log中添加深度参数用于递归

Adding depth parameter to console.log for recursion

本文关键字:参数 用于 递归 深度 添加 console log      更新时间:2023-09-26

我正在调试一个递归函数,如果我能跟踪深度就太好了。我试图编写一个console.log版本,该版本采用深度参数并在日志中添加相应数量的空间,但它不太正常工作。最大的问题是,jquery对象显示不同时,通过Chrome调试器运行。理想情况下,dlog函数应该与console.log相同,只是在前面加了n个空格,其中n = depth * 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>

我已经在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 + ' ');
}

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

// 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()调用相同,那么应该这样做…