将深度参数添加到console.log以进行递归 [英] Adding depth parameter to console.log for recursion
问题描述
我正在尝试调试递归函数,如果可以跟踪深度,那将是很好的.我试图编写一个console.log版本,该版本带有一个depth参数,并在日志中添加了相应数量的空格,但是效果不佳.最大的问题是,通过Chrome调试器运行时,jquery对象的显示方式有所不同.理想情况下,dlog函数与console.log相同,除了前n个空格(其中n = depth * 2).
I'm trying to debug a recursive function, and it would be nice if I could keep track of the depth. I attempted to write a version of console.log that took a depth parameter and prepended a corresponding number of spaces to the log, but it doesn't quite work right. The biggest problem is that jquery objects are displayed differently when run through the Chrome debugger. Ideally the dlog function would be identical to console.log except for prepending n spaces, where 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中实现了非常相似的功能,方法是将前缀字符串传递到日志记录函数中,并在每个递归级别上将空格附加到前缀字符串中.每次您要打印一些内容时,它可能比循环构造前缀字符串的效率更高.
I've implemented very similar functionality in Java and C by passing around a prefix string to the logging function and appending whitespace to the prefix string at each level of recursion. It's probably a bit more efficient than looping to construct the prefix string every time you want to print something.
因此,您可能会遇到诸如以下这样的运气:
So you might have better luck with something like:
// 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 + ' ');
}
这篇关于将深度参数添加到console.log以进行递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!