让我们按照模式进行一个相对简单的调用。这里又是函数:
function countdown(n) {
if (n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
}
假设你打电话给countdown(2):
循环 1:
1a) n不小于1
1b) arr 被初始化并设置为 countdown(1)
循环 2:
2a) n不小于1
2b) arr 被初始化并设置为 countdown(0)
循环 3:
3a) n 小于 1
3b) 一个空数组返回到循环 2
arr 是 []
循环 2 续
2c) arr.unshift 将数字 2 添加到数组的开头。
arr 是 [2]
2d) arr 返回到循环 1
循环 1 续
1c) arr.unshift 将数字 1 添加到数组的开头。
数组是 [1,2]
1d) arr 返回到函数调用
所以如果你写let result = countdown(2)和console.log(result),你会得到:[1,2]
让我烦恼的是,我不知道 const arr 何时或如何变为和
数组。
查看步骤 3b、2b 和 2c:
3b) an empty array is returned to loop 2
2b) an arr is initialized and set to countdown(0)
2c) arr.unshift adds the number 2 to the start of the array.
将一个空数组设置为const arr,然后将数字 2 添加到该数组中。
现在看看步骤 2d 和 1c:
2d) arr is returned to loop 1
1c) arr.unshift adds the number 1 to the start of the array.
该数组被设置为像这样 (const arr = [2]) 的 new 数组,并将数字 1 添加到该数组中。最后在 1d 中,该新数组返回给调用该函数的表达式。对于每个递归循环,你都有这样的东西:
const arr = something
new const arr = old const arr