我对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 :(有人能为这个程序提供一个修改以获得解决方案吗?使用递归函数编写这个程序基本可行吗?
发布于 2018-11-14 16:07:54
因为
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"));
}https://stackoverflow.com/questions/53304329
复制相似问题