简体   繁体   English

JS新手:如何正确调用HTML文档中的递归函数?

[英]Novice to JS: How to properly call a recursive function in an HTML document?

I'm a bit confused on calling the function correctly in this HTML doc. 对于在此HTML文档中正确调用该函数,我有些困惑。 What am I doing wrong? 我究竟做错了什么? The function should return the sum of all numbers between 1 and whatever number entered on the input field but is returning NaN instead. 该函数应返回1到在输入字段中输入的任何数字之间的所有数字的总和,但返回的是NaN。 How do I assign and display the returned value from the function to the disabled input field? 如何分配从函数返回的值并将其显示到禁用的输入字段?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Recursion</title>
    <script>
    let recursiveSum = (num) => {
        if (num === 1) {
            return 1;
        } else {
            return num + recursiveSum(num-1);
        }
    }
    </script>
</head>
<body>
   <h1>Find the sum of 1 to some number!</h1>
<form id="myForm" name="myForm">
  <input type="number" id="numInput" name="numInput" placeholder="Enter a positive number here" autofocus>
  <input type="text" id="sum" name="sum" disabled>
  <button type="button" onclick="recursiveSum(this.form.numInput.value);">Calculate! </button>
</form>
</body>
</html>

Currently your function doesn't explicitly return any value so undefined is returned from function implicitly. 当前,您的函数未显式返回任何值,因此undefined是从函数隐式返回的。

Also setting value in each recursive call doesn't make any sense. 在每个递归调用中设置value也没有任何意义。 You should set the value after the result of all the recursion. 您应该在所有递归的结果之后设置该值。

 const elm = document.getElementById("sum") function btnClick(num){ let recursiveSum = (num) => { if(num === 1) return 1; return num+recursiveSum(num-1) } elm.value = recursiveSum(+num) } 
 <h1>Find the sum of 1 to some number!</h1> <form id="myForm" name="myForm"> <input type="number" id="numInput" name="numInput" placeholder="Enter a positive number here" autofocus> <input type="text" id="sum" name="sum" disabled> <button type="button" onclick="btnClick(this.form.numInput.value);">Calculate! </button> </form> 

You need to separate the computation from showing the value, so you can properly compute the sum. 您需要将计算与显示值分开,以便可以正确地计算总和。 Once you got the sum, displaying it is easy. 一旦获得了总和,显示它就很容易。

 let recursiveSum = (num) => { if (num === 1) { return 1; } else { return num + recursiveSum(num - 1); } } let showSum = (num) => { document.getElementById("sum").value = recursiveSum(num); } 
 <h1>Find the sum of 1 to some number!</h1> <form id="myForm" name="myForm"> <input type="number" id="numInput" name="numInput" placeholder="Enter a positive number here" autofocus> <input type="text" id="sum" name="sum" disabled> <button type="button" onclick="showSum(parseInt(this.form.numInput.value));">Calculate! </button> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM