Javascript闭包教程

javascript closure tutorial from eloquent javascript

本文关键字:教程 闭包 Javascript      更新时间:2023-09-26

这个问题非常类似于这个线程Javascript..在本教程中完全丢失了。

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

我被卡在这部分了:

    find(start * 3, "(" + history + " * 3)"); 

每次start超出目标,它会做什么?它说返回null但是当我测试并在

上设置断点时
    if (start == goal) it shoes this on the console
    history: "(((((1 + 5) + 5) + 5) + 5) + 5)"
    start: 26
    history: "(((((1 + 5) + 5) + 5) + 5) * 3)"
    start: 63

它加起来*3,起飞+5,我不明白为什么。

返回语句

      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");

是包含"||"操作符的表达式。该运算符将使左侧被求值。如果结果不是null、0、false或空字符串,则返回该值。如果它是其中一个" false "值,则计算第二个表达式并返回。

换句话说,它可以重写成这样:

       var plusFive = find(start + 5, "(" + history + " + 5)");
       if (plusFive !== null)
         return plusFive;
       return find(start * 3, "(" + history + " * 3)")

如果"start"超过"goal",函数返回null。当然,如果两个选项都不起作用,那么整个东西将返回null。

表达式:

find(start + 5, "(" + history + " + 5)") || 
    find(start * 3, "(" + history + " * 3)")

将首先尝试求值:

find(start + 5, "(" + history + " + 5)")

如果返回值不是null、0、false或空字符串,则语句求值为返回值。如果返回值为null、0、false或空字符串,则接下来将计算以下内容:

find(start * 3, "(" + history + " * 3)")

如果返回值不是null、0、false或空字符串,则语句求值为返回值。如果返回值为null、0、false或空字符串,则该语句的计算结果为null、0、false或空字符串(以*3函数调用返回的值为准)。

所以这行:

return find(start + 5, "(" + history + " + 5)") || 
    find(start * 3, "(" + history + " * 3)")

就像是在说:"我要试着通过猜测这一步加5来找到解,如果这一步不行,我就试着在这一步乘以3,如果不行,我就放弃!"