求一个数字各个位数上的数字的和

如:123------------>1+2+3=6

function getEverySum(x){
    if (x<10){
        return x;
    }
    return x%10+getEverySum(parseInt(x/10));
}
console.log(getEverySum(123));

上面输出的结果是6,最后输入的数字可以任意更换成想要计算的数字。

猜你喜欢

转载自blog.csdn.net/weixin_41829477/article/details/81482783