我在学习时遇到了一个例子。当我稍加修改时,它将无法正常工作
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在忽略条件的情况下继续运行
为什么会这样?
答案 0 :(得分: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));