js递归无法正常赋值

错误:

var b = 10;
    var c = 0;
    var a = abc();
    function abc() {
      if (c == b){
        return 1
      } else{
        b--;
        abc()
      }
    }
    console.log(a)    //无法正确赋值   undefined

正确:

var b = 10;
    var c = 0;
    var a = abc();
    function abc() {
      if (c == b){
        return 1
      } else{
        b--;
        return abc()
      }
    }
    console.log(a)        // 1
原因:最后一次进行递归操作的时候值是返回了,但是只是返回到了递归自己调用的函数里,而最初的函数是没有返回值的·,所以打印出来就是undefined,如果想要函数最后一次计算所得值,就需要在每次调用该函数的时候进行return,每一次return都是把最新的函数调用返回到外层的函数调用,所以通过调用函数就能拿到值了。
原文地址:https://www.cnblogs.com/ash-sky/p/11081593.html