【问题标题】:Function does not return correct value when a string is returned instead of null [duplicate]当返回字符串而不是null时,函数不返回正确的值[重复]
【发布时间】:2020-07-02 22:05:32
【问题描述】:

我在学习时遇到了一个例子。当我稍作修改时,它将无法正常工作

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

这就是例子。但是,当我将 else if 语句中的 null 更改为如下示例中的字符串时。 else if 语句完全被忽略。下面的例子

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

      }
    }
    return find(1, "1");
  }

  console.log(findSolution(24)); 

在上面,if else 在忽略条件的情况下继续运行

为什么会这样?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    这里的重要部分是||

    return find(current + 5, `(${history} + 5)`) ||
           find(current * 3, `(${history} * 3)`);
    

    || 的工作方式,它将评估到 || 的左侧 如果 左侧是真的。否则,它将计算到右侧。

    在这里,如果您返回'impossible' 而不是null,您将返回一个非空字符串,这是真实的。因此,find 的父调用者将返回该真实字符串,而不是转到右侧的交替。

    要修复它,您可以改用=== 'impossible'

    if (left !== 'impossible') return left;
    return find(current * 3, `(${history} * 3)`);
    

    function findSolution(target) {
        function find(current, history) {
          if (current == target) {
            return history;
          } else if (current > target) {
             return "impossible";
          } else {
            const left = find(current + 5, `(${history} + 5)`);
            if (left !== 'impossible') return left;
            return find(current * 3, `(${history} * 3)`);
    
          }
        }
        return find(1, "1");
      }
    
      console.log(findSolution(24));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多