0
我正在玩coffescript中的一些算法,并以一些意想不到的输出结束。这里是我的代码:递归函数在结果中生成重复项
traverse = (tree, stack) ->
stack.push tree.node
if not tree.branches
stack
else
traverse branch, stack for branch in tree.branches
one = { node: 1 }
two = { node: 2 }
tree = { node: "+", branches: [one, two] }
console.log traverse one, [] # => [ 1 ]
console.log traverse two, [] # => [ 2 ]
console.log traverse tree, [] # => [ [ '+', 1, 2 ], [ '+', 1, 2 ] ]
我希望得到,而穿越tree
输出是[ '+', 1, 2 ]
但这被复制。我在这里错过简单的东西吗?
谢谢。
啊!你确实是对的。 for循环返回一个数组(外部[]),并且该栈是可变的。所以,即使我们第一次返回堆栈,值是[+ 1],它的值第二次被突变为[+ 1 2]。谢谢。 – j1n3l0 2013-04-06 18:18:48