Javascript在一个简单的阶乘函数上“过多递归”

时间:2016-07-29 06:05:18

标签: javascript recursion

我在这里找了几个“过多的递归”问题和答案,但每个都解决了一个特定的问题,但我无法从他们中推断出一个正确的答案来回答这个代码错误,如何解决它和为什么我会收到这个错误:

customer.findById(customerObject.id, function(err, objectResult){

    console.log(objectResult.imageIndex);

    if(!objectResult.imageIndex){
        objectResult.imageIndex = 1;
    }
    else{
        var index = objectResult.imageIndex;
        objectResult.imageIndex = index++;
        console.log(objectResult.imageIndex);
    }

    customer.upsert(objectResult, function(err, response){});
})

2 个答案:

答案 0 :(得分:5)

您需要传递参数值。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="number" id="num">
<input type="button" id="submit" value="Get Factorial" onclick="result()"><br>
<div id="yourResult"></div>
<script>

    function factor(n){
        if(n==0){
            return 1;
        }
        if(n==1){
            return 1;
        }
        return n * factor(n-1);
    }
    function result() {
        inputValue = document.getElementById('num').value;
        $('#yourResult').append('<p>your factorial of ' + inputValue + ' equals to: ' + factor(inputValue)+'</p>');
    }
</script>
</body>

答案 1 :(得分:1)

嘿@clusterBuddy让它变得正确document.getElementById('num').val  到document.getElementById('num').value并尝试下面的代码  给你阶乘结果:

<script type="text/javascript">
    function factor(){
    var n=document.getElementById("num").value;


      var factorial = function(n) {
        if(n == 0) {
            return 1
        } else {
            return n * factorial(n - 1);
        }

      }
      document.getElementById("yourResult").innerHTML ="your factorial is"+factorial(n);

  }
</script>
<body>
<input type="text" id="num">
<input type="button" id="submit" value="submit" onclick="factor()"><br>
<span id="yourResult"></span>
</body>