为何递归函数checkNumbers计算数字和时返回undefined?底层逻辑解析
undefined? First, let's look at the code you provided to set the context:
const checkNumbers = (membershipId) => { if (membershipId.length === 1) { return membershipId; } if (membershipId.length > 1) { sumOfNumbers = [...membershipId].reduce((a, b) => +a + +b, 0); checkNumbers(sumOfNumbers.toString()); } }; console.log(checkNumbers("555"));
How this function is supposed to work (its intended mechanism)
This is a recursive function meant to calculate the digital root (repeated sum of digits until only one digit remains) of the input number string. Let's walk through the execution with your test input "555":
- First call:
checkNumbers("555")– the input length is 3, so it splits the string into an array["5", "5", "5"], usesreduceto convert each character to a number and sum them (5+5+5=15), then converts that sum back to a string"15"and calls itself recursively with that value. - Second call:
checkNumbers("15")– input length is 2, so it sums 1+5=6, converts to"6"and recurses again. - Third call:
checkNumbers("6")– input length is 1, so it hits the firstifcondition and returns"6"(the correct result we want).
Why it returns undefined
The problem is a classic recursive mistake: you're not returning the result of the recursive call back up the call chain.
- When you call
checkNumbers(sumOfNumbers.toString())inside the secondifblock, you're executing the recursive function, but you never pass its return value back to the parent function call. - The first call to
checkNumbers("555")runs through the secondifblock, does the recursive call, and then… has noreturnstatement. In JavaScript, functions returnundefinedby default if no explicitreturnis specified. - Even though the innermost call correctly returns
"6", that value dies in the middle of the call stack because no upper layer catches it and returns it onwards.
Also, a side note: sumOfNumbers is not declared with let or const, which means it's being created as a global variable – that's a bad practice that can lead to unexpected bugs later.
Fixing the function
Just add a return before the recursive call, and declare sumOfNumbers properly:
const checkNumbers = (membershipId) => { if (membershipId.length === 1) { return membershipId; } if (membershipId.length > 1) { const sumOfNumbers = [...membershipId].reduce((a, b) => +a + +b, 0); return checkNumbers(sumOfNumbers.toString()); // Pass the recursive result back up } }; console.log(checkNumbers("555")); // Now logs "6" as expected
内容的提问来源于stack exchange,提问作者Yogaparthasarathy

