gpt4 book ai didi

javascript - 在递归函数中,在哪里存储结果?

转载 作者:行者123 更新时间:2023-11-30 07:46:21 25 4
gpt4 key购买 nike

我目前正在尝试让 JavaScript 为 boolean 函数生成真值表。给定一个函数,代码应该只列出所有可能的 boolean 组合,以及每个组合的函数输出。

至于生成所有组合,我将其放在一起(仅简化为组合代码):

var table = [];
function combinations(current) {
var current = current || [];
if(current.length === 3) {
table.push(current);
} else {
var c = copy(current);
c.push(true);
combinations(c);

c = copy(current);
c.push(false);
combinations(c);
}
}

function copy(a) {
var r = [];
for(var i = 0; i < a.length; i++) r.push(a[i]);
return r;
}

combinations(); // now table consists of each pair of 3 boolean values

所以基本上当它达到一个组合时(即 current.length === 3),它会将结果记录推送到 table。然而,我想知道这是否是存储递归函数结果的推荐方式。

我遇到了在递归函数中使用 return 的建议,但是如何实现这样的事情 - 即,如果 combinations 最后必须返回一个数组包含所有元素,怎么可能这样做?当然,最后我可以只使用 return table,但实际上我正在寻找一种方法来在函数内部完成所有这些操作,而无需像现在这样的外部变量。

那么,如何在不使用外部变量的情况下使组合将结果作为数组返回?

最佳答案

使用Array.concat() .

function combinations(current) {
var current = current || [];
if(current.length === 3) {
return [current];
} else {
return combinations(current.concat(true)).concat(combinations(current.concat(false)));
}
}

var table = combinations(); // now table consists of each pair of 3 boolean values

console.log(table);

更优雅,不是吗?

Demo →

关于javascript - 在递归函数中,在哪里存储结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5378603/

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