javascript闭包教程从雄辩的javascript [英] javascript closure tutorial from eloquent javascript

查看:146
本文介绍了javascript闭包教程从雄辩的javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题与此主题非常相似 Javascript..totally lost in this tutorial

the question is pretty similar to this thread Javascript..totally lost in this tutorial.

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

每次启动超出目标时它会做什么?它说它返回null,但当我测试和放置断点在

each time start goes beyond goal what does it do? it says it return null but when I test and put breakpoint on

    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

$ b

推荐答案

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

是一个涉及||运算符。该操作符将导致左侧被评估。如果结果不为null,零, false 或空字符串,那么将返回该值。如果它是那些falsy值之一,则第二个表达式被计算并返回。

is an expression involving the "||" operator. That operator will cause the left-hand side to be evaluated. If the result of that is not null, zero, false, or the empty string, then that value will be returned. If it is one of those "falsy" values, then the second expression is evaluated and returned.

换句话说,可以这样重写: p>

In other words, that could be re-written like this:

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

如果start超过goal,则函数返回null。当然,如果两个替代品不工作,那么整个事情将返回null。

If "start" ever exceeds "goal", the function returns null. Of course, if both the alternatives don't work, then the whole thing will return null.

这篇关于javascript闭包教程从雄辩的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆