5

我被困在以下功能上,该功能出现在我也查看过的其他一些帖子中。

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));

此链接中也给出了。

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

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

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

如何start从 6 到 3,然后再回到 11(第四个项目符号)?

4

1 回答 1

7

好的,这是使用控制台日志语句增强的代码版本。打开 Chrome/Opera/Firefox 开发者工具并在那里执行此代码:

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) );

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

于 2012-10-27T03:39:00.043 回答