令人沮丧的JS中的递归函数 [英] Frustrating recursive functions in JS

查看:33
本文介绍了令人沮丧的JS中的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这整天我一直在动脑筋,但我还是不明白.有人可以向我解释一下,该功能如何工作?!?!?!

I've been wracking my brain on this all day, and I still don't get it. Could someone please explain to me, how on earth does this function work?!?!?!

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

console.log(findSolution(24));
// → (((1 * 3) + 5) * 3)

它如何不保持在无限循环中来回调用自己的声音?

How does it not keep going back and forth calling on itself in an infinite loop?

推荐答案

基本上,该测试:

if (current == target) {
    return history;
}

测试是否找到解决方案,然后返回该解决方案

tests if the solution has been found, and then returns that solution

那次考试:

if (current > target) {
    return null;
}

发现 找不到解决方案 ,然后返回null.

finds out that no solution can be found, and then returns null.

例如,如果您尝试 findSolution(10),则会得到空值.

For example, if you try findSolution(10), you will get null.

否则,如果我们不在这些递归结束条件之一中,则代码将继续搜索并构建解决方案字符串.

Else, if we are not in one of those recursion ending conditions, the code will continue to search and to build the solution string.

因此,此代码将尝试构建"+5"和"* 3"的每种可能的组合,直到产生给定的数字,或者如果组合给出的数字更大,则为null.

So, this code will try to build every possible combination of "+5" and "*3" until it produces either the given number, or null if the combination gives a greater number.

这篇关于令人沮丧的JS中的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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