此递归代码中的空数组如何访问? [英] The empty array in this recursive code is accessible how?

查看:44
本文介绍了此递归代码中的空数组如何访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我辛苦地看着这个.我了解递归,了解调用堆栈和后进先出"的概念,但是在此示例中.

I have looked at this long and hard. I understand recursion, I understand the call stack and the concept of "Last in, first out" but in this example.

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]

当满足基本条件"并返回[]; 时,如果数组没有名称,如何访问该数组?什么时候名称 countArray 归属于此数组?

When we meet the 'base condition' and we return []; , how is the array accessible if it does not have a name? and when is the name countArray attributed to this array?

我就是不明白!

推荐答案

递归向下递归直到 n === 1 .然后,当调用 countup(0)时(作为 countup(1-1)时),将返回一个空数组.在同一时刻,在同一行上,该空数组分配给变量 countArray .从那里推送 1 ,并返回数组 [1] ,分配给 countArray 1级备份树,然后继续递归回到起始编号.

Recursion recurses down until n===1. Then, when countup(0) is called (as countup(1-1) , an empty array is returned. In that instant, on the same line, the empty array is assigned to the variable countArray. from there 1 is pushed, and the array [1] is returned, assigned to the countArray 1 level back up the tree, and you continue recursing back up to your starting number.

这是发生数组分配的行:

This is the line where the array assignment occurs:

const countArray = countup(n - 1);

调用该函数,并将该函数的返回结果分配给该变量.起初,它只是简单地递归到更深层次.然后,当 n == 1 时,它将停止递归,分配一个实际值,然后开始向上爬.
它需要这个确定的基本值 [] 才能爬出其最深层次的递归.

The function is called, and the return result of the function is assigned to the variable. At first it simply recurses to a deeper level. Then, when n==1, it stops recursing, gets assigned an actual value, and begins climbing back up.
It needs this definitive, base value, [] before it can climb out of its deepest level of recursion.

这篇关于此递归代码中的空数组如何访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆