javascript - 为什么它反向操作之后呢?
问题描述
我尝试使用递归的概念通过 JavaScript 添加一个从 1 到 10 的数字,但它没有按预期工作。它反转操作并得出第一个结果,当我使用变量存储结果时,我得到了undefined。这是代码
var total = 0, count = 1;
function sum(total, count){
if(count <= 3){
total +=count;
count++;
sum(total, count);
}else{
return total;
};
}
var result = sum(total, count);
console.log(result);
解决方案
你没有从你的第一个if
条件中恢复过来。任何函数的默认返回值都是undefined
.
var total = 0, count = 1;
function sum(total, count){
if(count <= 3){
total +=count;
count++;
return sum(total, count);
}else{
return total;
};
}
var result = sum(total, count);
console.log(result);
推荐阅读
- android - 无法解析 org.tensorflow:tensorflow-lite:0.0.0-nightly
- swift - 添加带有图像的 UINavigationbar 按钮时出错
- mysql - 为什么这个 mysql 查询在 Workbench 中执行但不使用 JDBC 调用时工作正常?
- python - Pyinstaller EXE 的 __file__ 指的是一个 .py 文件
- c++ - 带有两个输入参数的 std::vector 构造函数
- ios - 仅在表格视图中快速显示json数组中的重复元素一次
- windows-services - topshelf windows服务失败后没有重启
- python - Sympy - 将等价表达式与等号 (=) 进行比较
- python - 使用值的出现计数在熊猫中创建数据透视表
- reactjs - Azure AD B2C 未获得访问令牌