Eloquent Javascript的findSequence澄清

KMc*_*McA 5 javascript recursion

我仍然坚持以下功能,这个功能出现在我还评论过的其他一些帖子中.

function findSequence(goal) {
  function find(start, history) {
    if (start == goal)
      return history;
    else if (start > goal)
      return null;
   else
      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
 }
  return find(1, "1");
}

print(findSequence(24));
Run Code Online (Sandbox Code Playgroud)

也在此链接中给出.

Javascript ..在本教程中完全丢失了

在上面的解释中,答案试图将目标设定为11.它们的起点为1,首先针对11进行测试,然后是针对11进行测试的6的开始.

我理解前两个步骤.但是,我不理解从第二步(比较start:6到goal:11)到第三步(比较start:3到goal:11)的飞跃.

如何start从6,回到3,然后回到11(第四个子弹)?

c69*_*c69 7

好的,这是一个使用控制台日志语句增强的代码版本.打开Chrome/Opera/Firefox eveloper工具并在那里执行以下代码:

function findSequence (goal) {
  function find (start, history, depth) {
    depth = depth || 0;
    console.log( Array( ++depth ).join('--> '), start, goal, history );
    if (start == goal) {
      console.warn( 'history' );
      return history;
    } else if (start > goal) {
      console.error( 'null' );
      return null;
    } else {
      console.info('recursion!');
      return find(start + 5, "(" + history + " + 5)", depth) ||
             find(start * 3, "(" + history + " * 3)", depth);
    }
  }
  return find(1, "1");
}

console.info( findSequence(24) );
Run Code Online (Sandbox Code Playgroud)

您将获得此程序的调用跟踪,并希望通过查看跟踪来直观地掌握递归的概念.