我尝试重写此indexOf MDN示例以练习递归
var str = 'To be, or not to be, that is the question.';
var count = 0;
var pos = str.indexOf('e');
while (pos !== -1) {
count++;
pos = str.indexOf('e', pos + 1);
}
console.log(count); // displays 4
这是我的解决方案:
var count = 0;
function countLetters(str, p) {
var pos = str.indexOf(p);
if (pos == -1) {
return count;
}
else {
count ++;
return countLetters(str.substr(pos + 1), p)
}
}
console.log(countLetters('To be, or not to be, that is the question.', 'e'));
它可以工作,但是仍然可以在函数本身内部获取count变量吗?如果我在函数外部有一个count变量,那不是真的递归吗?
您可以做的是从方法中返回计数值,因此,如果找不到该项目,则返回0,否则返回 1 + value-of-recursive-call
function countLetters(str, p) {
var pos = str.indexOf(p);
if (pos == -1) {
return 0;
} else {
return 1 + countLetters(str.substr(pos + 1), p)
}
}
console.log(countLetters('To be, or not to be, that is the question.', 'e'));
演示:小提琴
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句