简体   繁体   English

我如何解决我一直从中得到的未定义结果?

[英]How do I fix the undefined result I keep getting from this?

So I'm doing the HackerRank superDigit challenge and even though I have the correct value for all the informal test cases, the Output box says that the result is undefined.所以我正在做 HackerRank superDigit 挑战,即使我有所有非正式测试用例的正确值,输出框说结果是未定义的。 I'm not really getting what undefined is all about or how a variable with a value returns as undefined.我并没有真正了解 undefined 是什么,或者一个带有值的变量如何返回为 undefined。

 function superDigit(n, k) { // Write your code here var nArr = []; for(let i = 0; i < n.length; i++) { nArr.push(n[i]); } console.log('nArr: ' + nArr); var nComb = 0; for(let i = 0; i < nArr.length; i++) { nComb += parseInt(nArr[i]); } console.log('nComb: ' + nComb); var nMult = nComb *= k; console.log('nMult: ' + nMult); console.log(''); if(nMult < 10) { return nMult; } else { superDigit(nMult.toString(),1); } }

You probably want to return the superDigit result as well.您可能还想返回superDigit结果。 So when calling superDigit recursively, add the return statement.所以在递归调用superDigit时候,加上return语句。 I also cleaned up the console.log calls a bit so its more readable to me.我还稍微清理了console.log调用,这样它对我来说更具可读性。

 function superDigit(n, k) { var nArr = []; for(let i = 0; i < n.length; i++) { nArr.push(n[i]); } var nComb = 0; for(let i = 0; i < nArr.length; i++) { nComb += parseInt(nArr[i]); } var nMult = nComb *= k; console.log('nMult:', nMult, 'nArr:', nArr, 'nComb:', nComb); if(nMult < 10) { return nMult; } else { return superDigit(nMult.toString(),1); } } document.getElementById('result').innerText = superDigit("200", 20);
 <html> <body> <p id="result"></p> </body> </html>

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

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