简体   繁体   中英

how to call the function inside itself in javascript?

I am a beginner in JavaScript and I faced this test on one of testing websites and they gave me this test which is a function that convert given number to checkId which is the sum of all digits of the given number for example: given 237 its 2+3+7=12 12 is 1+2= 3 so the returned value should be 3 this is my code and the problem it gives me UNDEFINED please help thank you

 function createCheckDigit(membershipId) { if (membershipId < 10) { return membershipId; } else { var digits = ("" + membershipId).split(""); for (var i = 0; i < digits.length; i++) { digits[i] = parseInt(digits[i]); } var res = digits.reduce((a, b) => a + b, 0); // recursion createCheckDigit(res); } } document.write(createCheckDigit("450"));

You were just missing to return the result of the inner call:

 function createCheckDigit(membershipId) { if (membershipId < 10) { return membershipId; } else { var digits = ("" + membershipId).split(""); for (var i = 0; i < digits.length; i++) { digits[i] = parseInt(digits[i]); } var res = digits.reduce((a, b) => a + b, 0); // missing return here return createCheckDigit(res); } } document.write( "450 => "+createCheckDigit("450")); document.write( "<br>730 => "+createCheckDigit("730")); document.write( "<br>480 => "+createCheckDigit("480"));

In recursive function, if function returns the value then you must return function call too for get value.

Here is the solution:

 function createCheckDigit(membershipId) { if (membershipId < 10) { console.log("member", membershipId); return membershipId; } else { var digits = ("" + membershipId).split(""); console.log("digit", digits); for (var i = 0; i < digits.length; i++) { digits[i] = parseInt(digits[i]); } var res = digits.reduce((a, b) => a + b, 0); console.log("result", res); // recursion return createCheckDigit(res); } } document.write(createCheckDigit("450"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM