返回值始终未定义

时间:2020-07-19 14:29:02

标签: javascript node.js undefined return-value

我正在尝试使用递归来实现GCD功能,但是当我返回一个值时,它总是返回undefined,而如果我创建了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 = b
    b = a % b
    a = temp
    if (b === 0) {
      gcd = a
      return gcd
    }
    gcdRec(a, b)
  }
}

在使用gce之前,我还尝试将其定义为let gcd =0,然后定义为gcd = gcdRec(a,b),但是仍然相同。你知道为什么要这么做吗?

1 个答案:

答案 0 :(得分:2)

针对每种情况在函数中提供return语句

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 = b
    b = a % b
    a = temp
    if (b === 0) {
      gcd = a
      return gcd
    }
   return gcdRec(a, b)
  }
}