gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:45:36 25 4
gpt4 key购买 nike

我写了一个基于三 Angular 数的递归函数。当将多个人传递给该函数时,它会返回他们之间可能的连接数。这工作正常,但我想将此函数的每次迭代返回到一个数组中 - 因为我随后计划将此列表显示到屏幕上。这个新函数将返回一个数组,例如 [1,3,6,10]。

我不知道我是否可以在我现有的函数中执行此操作,或者我是否需要某种辅助/辅助函数。传回我当前函数的返回值是人数(而不是连接数),所以我想我要么需要在这个函数中添加一个额外的参数,要么写另一个完全与它一起操作.

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

我的函数代码如下:

function connection(numberOfPeople) {

if (numberOfPeople == 1) {
return 0;
}

const returnVal = (connection(numberOfPeople-1) + (numberOfPeople-1));
console.log(returnVal);

return returnVal;
}

最佳答案

...so I would think I either need to add an additional parameter into this function...

没错!像这样(请参阅指示的更改/添加):

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; // <===
}

请注意,由于结果是在递归之后推送的,因此数组将以 last 计算的值结束,然后是倒数第二个,然后是倒数第三个,依此类推。

关于javascript - 如何将递归函数的每次迭代返回到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com