递归函数如何处理||操作员? [英] How does Recursion Function handle the || operator?

查看:44
本文介绍了递归函数如何处理||操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function findSolution(target) {
    function find(current, history) {
      if (current == target)
        {debugger;
        return history;
        }
      else if (current > target){
        debugger;
        return null;
      }
      else{
        debugger;
        return find(current + 5, "(" + history + " + 5)") ||
              find(current * 3, "(" + history + " * 3)");
      }
    }
    debugger;
    return find(1, "1");
  }

  console.log(findSolution(13));

在到达find(33,((((1 + 5)+ 5)* 3)")之后,它在工作期间为什么会从较早的时间删除+5,而不是刚才调用的* 3?

During it's working after it reaches find(33, "(((1 + 5) + 5) * 3)") why does this remove +5 from earlier and not *3 it just called?

代码的工作方式:

find(1, "1")
 find(6, "(1 + 5)")
  find(11, "((1 + 5) + 5)")
    find(16, "(((1 + 5) + 5) + 5)")
      too big
    find(33, "(((1 + 5) + 5) * 3)") //why does this remove +5 from earlier and not *3 it just called
      too big 
  find(18, "((1 + 5) * 3)")
    too big
find(3, "(1 * 3)")
  find(8, "((1 * 3) + 5)")
    find(13, "(((1 * 3) + 5) + 5)")
      found!

推荐答案

每次调用 find()都会产生新的本地历史记录.您的递归调用不会更改 history ;他们制作了新的琴弦.

Every invocation of find() results in a new local history. Your recursive calls do not change history; they make new strings.

因此进入

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

首先以 + 5 形式调用该函数,如果返回 null ,则以 * 3 形式调用该函数.因此,永远不会删除" + 5 ;该字符串将被简单丢弃.

the function is called with the + 5 form first, and if that returns null then it's called with the * 3 form. So the + 5 is never "removed"; that string is simply discarded.

此外,对于 || ,如果左侧表达式返回非null,则完全不评估右侧.

Also, as to the ||, if the left-hand expression returns non-null, then the right-hand side is not evaluated at all.

这篇关于递归函数如何处理||操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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