为什么我必须先将此 Javascript 对象存储在变量中,然后再将其推送到数组?

Why do I have to store this Javascript object in a variable before pushing it to an array?

我正在使用这个有效的递归函数在 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