javascript - 递归函数未按预期返回值
问题描述
在这个函数中,我试图计算方法的数量,一个数字可以被解码。1 应该被解码为 a, 3 为 c, 26 为 z 。该函数计算正确的计数,但只返回未定义的。我认为它应该在正确的时间取消递归调用,然后我到达“转义”块,但该数字没有按应有的方式返回。谁能指出我的原因,为什么会这样?
function numWaysDecodable(msg) {
msg = msg.toString().split("");
function helper(msg, past = 99, count = 1) {
if (msg.length === 0) {
console.log("wtf count is:"+count);
return count;
}
let head = msg.shift();
if (head < 7 && past < 3) {
count++
}
//the below return statement was missing
return helper(msg, head, count);
}
return helper(msg);
}
console.log(numWaysDecodable(123));
- 12 1 2;
- 1 2 12;
- 12 12;
- 1 2 1 2;
- 1 21 2;
我认为代码错过了 nr.3,12 12; 我不确定如何解决这个问题。还有一些想法要做
解决方案
您必须在递归函数的每次调用中返回值,例如:
return helper(msg, head, count);
function numWaysDecodable(msg) {
msg = msg.toString().split("");
function helper(msg, past = 99, count = 1) {
if (msg.length === 0) {
console.log("wtf count is:"+count);
return count;
}
let head = msg.shift();
if (head < 7 && past < 3) {
count++
}
return helper(msg, head, count);
}
return helper(msg);
}
console.log(numWaysDecodable(123));
推荐阅读
- powershell - 输出表 w。自定义属性显示错误计数?
- ios - iPhone 11 和/或 iOS 13 的 iBeacon 监控/测距问题
- css - 希望将滑块中的图像垂直对齐到中间
- ubuntu - Apache Guacamole 登录无效
- c# - 如何修复此错误(System.Windows.Forms.DataGridViewCell.Value.get 返回 null。)
- javascript - 在javascript中从另一个列表中删除一个列表的内容时出现问题
- mongodb - 由于子数组展开后重复,Mongo 父总和错误
- java - 如何让我的程序等到任务完成后再继续?
- python - 给定小数位数的平方根近似值
- android - Where does this rocket app icon come from?