Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要解释的Javascript代码(递归示例)_Javascript - Fatal编程技术网

需要解释的Javascript代码(递归示例)

需要解释的Javascript代码(递归示例),javascript,Javascript,我的主要问题是,我似乎无法理解如何在纸上解决问题,更不用说理解代码或编写自己的代码了。这是我正在读的一本书《雄辩的JavaScript》的摘录 考虑一下这个难题:从数字1开始,反复加5或乘以3,就可以产生无限多的新数字。如果给定一个数字,你将如何编写一个函数来尝试寻找产生该数字的加法和乘法序列 例如,数字13可以通过先将1乘以3,然后再加5两次来达到。15号电话根本打不通 以下是解决方案: function findSequence(goal) { function find(start

我的主要问题是,我似乎无法理解如何在纸上解决问题,更不用说理解代码或编写自己的代码了。这是我正在读的一本书《雄辩的JavaScript》的摘录

考虑一下这个难题:从数字1开始,反复加5或乘以3,就可以产生无限多的新数字。如果给定一个数字,你将如何编写一个函数来尝试寻找产生该数字的加法和乘法序列

例如,数字13可以通过先将1乘以3,然后再加5两次来达到。15号电话根本打不通

以下是解决方案:

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

“那你的问题是什么?”穆塞凡我想他想解释一下code@Harikrishnan:是的。。。那是不会发生的为什么不呢?这和其他任何问题一样都是一个编程问题。@ThaMe90:从技术上讲,根本没有任何问题,只是一个命令。而且,这种事情不符合SO规则,主要是因为它太具体了。然后我们必须考虑为什么OP的书还不能解释它做什么,非常无用的书iMo谢谢你SJE397。我会研究你的意见。那么你认为这是一个可以接受的问题吗?也许不太具体?你认为“explain findSequence function from Elount JavaScript book”是一个常见的搜索词吗?@musefan是的……可以在问题标题中使用“递归”一词。它可能使用递归,但这是一个可怕的例子。如果有人想理解递归,那么这不是用来解释的最友好的代码。我真的不这么认为,这是一个可以问“解释我已经运行的代码”类型问题的地方。我不想让任何不被理解的代码通过。我试图找到我自己的解决办法,但不是这样的。作者试图解释代码,但实际上是用技术术语解释的。所以我想对代码进行第二次解释。一个来自同龄人的,我可以理解这一点。对不起,如果我违反了任何规则。
function findSequence(goal) {

   // define a function that has a 'start' number (current total),
   // and a string that is the history of what we've done so far
   // (and note that for this function, the 'goal' parameter above is in scope).
   function find(start, history) {
     // if we've reached the goal, return the string that says how we got there
     if (start == goal)
      return history;
     // if we've overshot, return null
     else if (start > goal)
       return null;
     else
       // call this same function (recursion) with two different possibile ways of
       // getting closer to the goal - one adding 5 and one multiplying by 3...
       // the or ('||') operator will return the first of the two that is not null
       return find(start + 5, "(" + history + " + 5)") ||
              find(start * 3, "(" + history + " * 3)");
   }
   // start at 1
   return find(1, "1");
 }