我正在使用这个递归函数在 Javascript 中生成一棵树,它的工作原理是:
function generate(depth){
console.log('call '+depth);
created_children = [];
if (depth < 3) {
for (i=0; i<3; i++){
new_child = generate(depth+1);
created_children.push(new_child);
}
console.log(created_children);
return {text: 'lorem', children: created_children};
}
else
return {text: 'lorem'};
}
但是,当我像这样将子节点附加到 created_children
时,created_children
为空。
function generate(depth){
console.log('call '+depth);
created_children = [];
if (depth < 3) {
for (i=0; i<3; i++){
created_children.push(generate(depth+1));
}
console.log(created_children);
return {text: 'lorem', children: created_children};
}
else
return {text: 'lorem'};
}
为什么 JavaScript 会有这样的行为?变量是否必须在本地范围内命名才能将其推送到数组?这和惰性求值有关系吗?
谢谢, 路易丝
最佳答案
不要在递归中使用全局变量(或者任何地方,但这只是我的观点),这是一个不好的做法。下面的代码工作得很好:
function generate(depth){
if (depth < 3) {
var created_children = [];
for (i=0; i<3; i++){
created_children.push(generate(depth+1));
}
return {text: 'lorem', children: created_children};
}
else
return {text: 'lorem'};
}
var tree = generate(0);
console.log(JSON.stringify(tree));
您可以查看here
关于javascript - 为什么我必须先将此 Javascript 对象存储在变量中,然后再将其推送到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35314081/