Javascript:在递归函数中初始化变量一次(就像静态变量一样)
我有一个递归函数,它返回树的叶节点(以嵌套对象的形式): 此函数的问题是,它对单个对象(树)的效果非常好,但当在参数中传递另一个对象时,它只是将叶节点附加到已从上一棵树获得的叶节点上 比如说,Javascript:在递归函数中初始化变量一次(就像静态变量一样),javascript,recursion,static-members,Javascript,Recursion,Static Members,我有一个递归函数,它返回树的叶节点(以嵌套对象的形式): 此函数的问题是,它对单个对象(树)的效果非常好,但当在参数中传递另一个对象时,它只是将叶节点附加到已从上一棵树获得的叶节点上 比如说, // gets the leaf nodes of obj1 tree obj1_leaves = retrieve(obj1) // instead of only getting leaf nodes of obj2, it appends them to leaf nodes of obj1 o
// gets the leaf nodes of obj1 tree
obj1_leaves = retrieve(obj1)
// instead of only getting leaf nodes of obj2, it appends them to leaf nodes of obj1
obj2_leaves = retrieve(obj2)
现在出现这种情况的原因是typeof retrieve.names==“undefined”
仅第一次为真。每当再次调用此函数时,检索
函数的成员名称
(也可以被视为对象)已经设置/初始化
是否有一种方法可以在递归函数中仅为给定函数调用设置变量(或对象的成员),然后为另一个函数调用再次取消设置/设置它 您可以使用内部函数:
function retrieve(a) {
var names = [];
function _retrieve(a) {
if (a.left != null)
_retrieve (a.left)
if (a.right != null)
_retrieve (a.right)
if (a.left == null && a.right == null)
names.push(a)
}
_retrieve(a);
return names;
}
outer函数将空数组初始化为局部变量。内部函数的工作与原始函数基本相同,但它引用了该局部数组
每次调用retrieve()
,都会创建一个新的本地数组并用于遍历树。另一种方法(对于@Pointy给出的方法,我不再重复)是使用可选参数。它仅在“第一个”(最外面的调用)上填充默认值,然后传递给每个递归调用
function retrieve(a, names) {
if (!names) names = [];
if (a.left != null)
retrieve(a.left, names);
if (a.right != null)
retrieve(a.right, names);
if (a.left == null && a.right == null)
names.push(a);
return names;
}
对不要让它是静态的。我感觉你实际上想要使用两个函数。这种方法的问题是,每次调用
retrieve
时,它都会设置names=[]
,甚至是递归的。我不希望发生这种情况。@SaadH啊,对不起,这是一个错误-我会编辑question@SaadH现已修复-递归调用是对内部函数\u retrieve
,而不是retrieve
。有点像通过递归调用进行累加的“累加器”。
function retrieve(a, names) {
if (!names) names = [];
if (a.left != null)
retrieve(a.left, names);
if (a.right != null)
retrieve(a.right, names);
if (a.left == null && a.right == null)
names.push(a);
return names;
}