简体   繁体   English

如何在javascript内部调用function?

[英]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我是 JavaScript 的初学者,我在一个测试网站上遇到了这个测试,他们给了我这个测试,它是一个 function,它将给定的数字转换为 checkId,它是给定数字的所有数字的总和,例如:给定 237 它的 2 +3+7=12 12 是 1+2= 3 所以返回值应该是 3 这是我的代码,它给我的问题是 UNDEFINED 请帮忙谢谢

 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.在递归 function 中,如果 function 返回值,则必须return function call以获取值。

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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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