试图理解为什么函数在递归函数中返回undefined

时间:2017-06-08 03:27:05

标签: javascript recursion

我无法理解在这个递归函数中发生的事情。 为什么y === undefined ??

function f(num){
  if(num !== 10){
    f(num + 1);
  } else {
    return num;
  }

}

var y = f(0);
console.log(y);

如果我在返回之前记录“num”,则值为10。 这是一个jsfiddle: https://jsfiddle.net/

2 个答案:

答案 0 :(得分:2)

如果num不是10,你只需再次调用f。从f返回的值不会在任何地方分配。你应该返回那个值。

[info] Updating {file:/home/tushar/lsbt/tasky/}tasky...
[info] Resolving org.scalatest#scalatest;3.0.1 ...
[warn]  module not found: org.scalatest#scalatest;3.0.1
[warn] ==== local: tried
[warn]   /home/tushar/.ivy2/local/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /home/tushar/.sbt/preloaded/org.scalatest/scalatest/3.0.1/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////home/tushar/.sbt/preloaded/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom
[warn] ==== Artima Maven Repository: tried
[warn]   http://repo.artima.com/releases/org/scalatest/scalatest/3.0.1/scalatest-3.0.1.pom 
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.scalatest#scalatest;3.0.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn] 
[warn]  Note: Unresolved dependencies path:
[warn]      org.scalatest:scalatest:3.0.1 (/home/tushar/lsbt/tasky/built.sbt#L4-5)
[warn]        +- default:tasky_2.10:0.1.0
[trace] Stack trace suppressed: run last *:update for the full output.
[error] (*:update) sbt.ResolveException: unresolved dependency: org.scalatest#scalatest;3.0.1: not found

答案 1 :(得分:1)

如果阻止,你应该在内部返回f(num + 1)。  没有它,除了“num”达到10之外什么也不返回。

 function f(num){
      if(num !== 10){
        return f(num + 1);
      } else {
        return num;
      }
    }
var y = f(0);
console.log(y);
// 10