我是 JavaScript 编程的新手,但我有很多其他编程语言的经验。 JavaScript 中的递归函数 的想法对我来说是一个新鲜的主题,我在使用过的其他语言中没有看到任何类似的东西。所以为了练习,我决定用“for循环”来编写一些我已经写过的程序。
其中一个程序是一个函数,它将字符串作为参数并报告其中有多少个 B 字母。使用面向目标的编程,我首先声明了一个函数,它可以找到一个字符串中任何其他字符的数量。程序如下,
function countChar(string, char) {
let counted = 0;
for (let index = 0; index < string.length; index++) {
if (string[index].toUpperCase() == char.toUpperCase()) {
counted += 1;
}
}
return counted;
}
function countBs(text) {
return countChar(text, 'B');
}
console.log(countBs('Baby'));
// output = 2
它工作得很好,但现在我正在使用递归函数,我得到了“最大调用堆栈大小”错误。我的递归函数程序看起来像这样,
function countChar(string, char) {
function cursor(i, counted) {
if (i == string.length) {
return counted;
} else if (string[i].toUpperCase() == char.toUpperCase()) {
return cursor(i++, counted++);
} else {
return cursor(i++, counted);
}
}
return cursor(0,0);
}
function countBs(text) {
return countChar(text, 'B');
}
console.log(countBs('Baby'));
// output must be 2 but I get 'Maximum call stack size' error instead :(
任何人都可以修改这个程序以获得解决方案吗?基本上可以用递归函数来写这个程序吗?
最佳答案
因为
return cursor(i++, counted++);
必须是
return cursor(i + 1, counted + 1);
(因为你想增加递归传递的值,而不是局部变量 i)
我会怎么做:
const countBs = (str, i = 0) =>
i >= str.length
? 0
: countBs(str, i + 1) + (str[i].toUpperCase() === "B");
或者,如果您打算将它用于非常非常长的字符串,请考虑 TCO:
function countBs(str, i = 0, count = 0) {
if(i >= str.length) return count;
return countBs(str, i + 1, count + (str[i].toUpperCase === "B"));
}
关于javascript - 运行简单递归函数时的最大调用堆栈大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53304329/