function numberSum(num) {
var str = num.toString();
var arrNum = str.split('').map(Number);//arrNum = [1, 2, 3];
//For-looping
var result = 0;
for (var i = 0; i < arrNum.length; i++) {
result = result + arrNum[i];
}
return result;
}
console.log(numberSum(22222)); // 2 + 2 + 2 + 2 + 2 = 10
ilterate我這樣做是與對於套住,然後重複它。問題是,我如何做到這一點,但遞歸函數?
請參閱[將循環(while/for)轉換爲遞歸或從遞歸轉換爲循環的一般方法?](https://softwareengineering.stackexchange.com/questions/279004/general-way-to-convert- a-loop-while-for-to-recursion-or-from-acursion-to-a) –
通過遞歸調用一個函數 –