首页 > 解决方案 > 为什么它反向操作之后呢?

问题描述

我尝试使用递归的概念通过 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);

标签: javascriptrecursionsum

解决方案


你没有从你的第一个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);


推荐阅读