[英]Function return on an int returns undefined
我正在制作一個簡單的 function,它將一串數字中的每個數字相加,直到它成為一個單元,例如“55555”-> 5+5+5+5+5 = 25->2+5 = 7 但我的 function總是返回 undefined,代碼有效,我可以 console.log 正確答案,但實際 function 總是返回 undefined
function createCheckDigit(membershipId) {
checkDigit = 0
for (i = 0; i < membershipId.length; i++) {
checkDigit += parseInt(membershipId.substring(i, i + 1));
}
if (checkDigit.toString().length > 1) {
createCheckDigit(checkDigit.toString())
} else {
return checkDigit;
}
}
如果我在 function 的 else 語句中使用console.log(checkDigit)
調用createCheckDigit("55555")
它顯示 7 是正確的,但 function 本身總是返回未定義
創建遞歸函數時,需要return
遞歸函數調用的結果。
return createCheckDigit(checkDigit.toString());
另外,請注意,在使用parseInt
時,建議將10
作為第二個參數傳遞,以確保它返回您期望的值。
function createCheckDigit(membershipId) { let checkDigit = 0 for (let i = 0; i < membershipId.length; i++) { checkDigit += parseInt(membershipId.substring(i, i + 1), 10); } if (checkDigit.toString().length > 1) { return createCheckDigit(checkDigit.toString()) } else { return checkDigit; } } console.log(createCheckDigit('55555'));
我還使用let
僅在函數范圍內聲明您的變量checkDigit
和i
而不會泄漏到全局范圍內。
需要在遞歸調用上添加return
語句,否則遞歸調用的結果會丟失:
function createCheckDigit(membershipId) { let checkDigit = 0; for (let i = 0; i < membershipId.length; i++) { checkDigit += parseInt(membershipId.substring(i, i + 1)); } if (checkDigit.toString().length > 1) { return createCheckDigit(checkDigit.toString()); } else { return checkDigit; } } console.log(createCheckDigit("55555"));
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
但是,我更願意始終將遞歸調用的基本條件放在開頭。 此外,使用String.split()和Array.reduce()您可以執行以下操作:
function createCheckDigit(membershipId) { if (!parseInt(membershipId) || membershipId.length <= 1) return isNaN(+membershipId) ? 0 : +membershipId; return createCheckDigit( membershipId.split("").reduce((acc, n) => ((+acc) + (+n)).toString()) ); } console.log("Result for '55555':", createCheckDigit("55555")); console.log("Result for null:", createCheckDigit(null)); console.log("Result for undefined:", createCheckDigit(undefined)); console.log("Result for '1':", createCheckDigit("1")); console.log("Result for 'foo':", createCheckDigit("foo"));
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
請注意使用一元加運算符將數字從字符串強制轉換為數字,來自MDN :
一元加法是將某物轉換為數字的最快和首選方式
您可以使用Array.prototype.reduce()並執行如下遞歸函數:
const sumDigit = x => `${x}`.length > 1 ? sumDigit([...`${x}`].reduce((sum, x) => sum + (+x), 0)) : +x; console.log(sumDigit('55555')); // 7 console.log(sumDigit('5555')); // 2
function calculateNm(numbers) {
let num = numbers.split("");
let newNum = num.reduce((acc, curr) => parseInt(acc) + parseInt(curr));
if (newNum.toString().length > 1) {
return calculateNm(newNum.toString());
} else {
return newNum;
}
}
calculateNm("55555");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.