javascript - 对输入的javascript执行递归函数
问题描述
我正在尝试运行一个递归函数来计算 HTML 输入中数字的阶乘。我已经知道如何通过迭代来做到这一点,我想递归地实现结果。但是当我这样做时,我得到一个“递归过多”的错误。我错过了什么?
HTML
<input type="text" name="factorial_input" placeholder="Enter a number">
<div class="button" onclick="calculateFactorial()">Let's see the factorial</div>
JS
function calculateFactorial(getInputValue) {
getInputValue = document.querySelector("input").value;
if (!getInputValue) {
console.log("You must enter a number");
} else if (getInputValue == 0) {
return console.log("1");
} else {
return console.log(getInputValue *= calculateFactorial(getInputValue - 1));
}
// console.log(getInputValue);
}
解决方案
您遇到了无穷无尽的递归问题,因为您正在从递归函数的输入中检索值,这就是getInputValue
变量每次都获得新值的原因。这是你做的错误的实现。试试下面给出的例子。
的HTML
<input type="text" name="factorial_input" placeholder="Enter a number">
<div class="button" onclick="calculateFactorial()">Let's see the factorial</div>
剧本
function calculateFactorial(getInputValue) {
let getInputValue = parseInt(document.querySelector("input").value);
console.log(fact(getInputValue));
}
function fact(n){
if (n === undefined) {
return 0;
} else if (n === 0) {
return 1;
} else {
return n *= fact(n - 1);
}
}
递归函数需要满足条件才能从recursion返回调用栈。否则,它会去无休止的调用。
推荐阅读
- reactjs - React Bootstrap - [HMR] 等待来自 WDS 错误的更新信号
- javascript - 如何在 react-native (web/android/ios) 中的图像上创建链接?
- laravel - [Route: patients.destroy] [URI: {language}/patients/{patient}] 缺少必需的参数。(资源/视图/患者/index.blade.php)
- python - IMAP 消息获取 UnicodeDecodeError 'utf-8' codec can't decode
- python - Python pd.read_csv:如何通过循环读取文件?
- sql - 在 PostgreSQL 数据库上更新查询间歇性缓慢
- javascript - 如果存在则更新 Many,否则为每个不存在的 LeadId 创建一个新 Document
- javascript - 如何使用 DOM 为 CSS 元素提供增量坐标?
- reactjs - 在 ReactJS 中获取 3 个单独的 div 的位置
- xml - 如何区分具有相同名称的不同 XML 属性?