如何将递归函数的每次迭代返回到另一个函数中



我写了一个基于三角数的递归函数。当多个人被传递到函数中时,它会返回他们之间可能的连接数。这很好,但我想把这个函数的每一次迭代都返回到一个数组中,因为我计划在屏幕上显示这个列表。这个新函数将返回一个数组,例如[1,3,6,10]。

我不知道我是否可以在我预先存在的功能中做到这一点,或者我是否需要某种辅助/次要功能。传递回我当前函数的返回值是人数(而不是连接数(,所以我认为我要么需要在这个函数中添加一个额外的参数,要么写另一个参数来完全与它一起操作。

它看起来应该很简单,我已经成功地在每次迭代中生成了一个值的控制台日志——问题是我需要将这些值添加到另一个数组中,并且只有在递归函数完成时才能返回这个数组。

我的函数代码如下:

function connection(numberOfPeople) {
if (numberOfPeople == 1) {
return 0;
}
const returnVal = (connection(numberOfPeople-1) + (numberOfPeople-1));
console.log(returnVal);
return returnVal;
}

。。。所以我想我要么需要在这个函数中添加一个额外的参数。。。

没错!像这样(参见所示的更改/添加(:

function connection(numberOfPeople, theArray = []) {
// -----------------------------^
let returnVal;                // <===
if (numberOfPeople == 1) {
returnVal = 0;            // <=== Didn't return here so we have a common
} else {                      //      path at the end
returnVal = (connection(numberOfPeople-1, theArray) + (numberOfPeople-1));
// ---------------------------------------------^
}
console.log(returnVal);
theArray.push(returnVal);     // <===
return theArray;              // <===
}

注意,由于结果是在递归后推送的,因此数组将以计算出的最后一个值结束,然后是倒数第二个值,再是倒数第三个值,等等。

function getConnections(numberOfPeople){
var connections =[];
(function connection(numberOfPeople) {
if (numberOfPeople == 1) {
return 0;
}
let returnVal = connection(numberOfPeople-1) + numberOfPeople-1 ;
connections.push(returnVal)
return returnVal 
})(numberOfPeople)
return connections
}
console.log(getConnections(5))

闭包是指函数"记住"其词法范围,即使函数在该词法范围之外执行。

由于函数的闭包属性,连接函数将具有connections变量的引用。

IIFE(立即调用函数表达式(是一个JavaScript定义后立即运行的函数。更多详细信息

我们使用IIFE函数来执行连接方法,而不会污染外部作用域。

提醒一下,这可以通过简单地调用连接函数来完成。

function getConnections(numberOfPeople){
var connections =[];
function connection(numberOfPeople) {
if (numberOfPeople == 1) {
return 0;
}
let returnVal = connection(numberOfPeople-1) + numberOfPeople-1 ;
connections.push(returnVal)
return returnVal 
}
connection(numberOfPeople)
return connections
}
console.log(getConnections(5))

最新更新