繁体   English   中英

返回值始终未定义

[英]Return value always undefined

我正在尝试使用递归实现 GCD function,但是当我创建返回值时,它总是返回未定义,而如果我创建了一个 console.log(value),它会正确显示吗?

这是我正在使用的代码:

 let a = 6 let b = 4 var gcd = gcdRec(a, b) console.log(gcd) //this executes undefined function gcdRec(a, b) { var gcd = 0 if (a % b === 0) { gcd = b return gcd //if i used console.log(gcd) it prints correctly } else { var temp = bb = a % ba = temp if (b === 0) { gcd = a return gcd } gcdRec(a, b) } }

我也尝试在使用它之前定义 gce,因为let gcd =0然后gcd = gcdRec(a,b) ,但它仍然是一样的。 知道为什么要这样做吗?

为每个条件在 function 中给出返回语句

 let a = 6 let b = 4 var gcd = gcdRec(a, b) console.log(gcd) //this executes undefined function gcdRec(a, b) { var gcd = 0 if (a % b === 0) { gcd = b return gcd //if i used console.log(gcd) it prints correctly } else { var temp = bb = a % ba = temp if (b === 0) { gcd = a return gcd } return gcdRec(a, b) } }

暂无
暂无

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

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