我对js很陌生,也不知道如何console.log我想要的东西,而不是"空";让我有点头疼。
我有这个代码(它来自一本名为"Eloquent JavaScript"的书(
function findNumber(number) {
function checkingForSolution(current, history) {
if (current == number) {
return history;
} else if (current > number) {
return null;
} else {
return (
checkingForSolution(current + 5, `(${history} + 5)`) ||
checkingForSolution(current * 3, `(${history} * 3)`)
);
}
}
return checkingForSolution(1, '1');
}
console.log(findNumber(34));
它通过将数字乘以3或加5来找到一个数字。我想添加console.log,这样它就会打印出类似";抱歉找不到算法";而不是";空";
我无法解决的问题是,如果我在函数中检查空值,当找到算法时,它只会打印console.log而不是算法。当函数搜索解时,它得到多个";null";
我试过这种
if(findNumber.checkingForSolution == null){
console.log('sorry')
}
else{console.log(findNumber(34));
}
但即使可以找到该算法,它也只是打印";对不起"有人能帮忙吗?
您可以在递归函数的第一次调用后添加默认值。
在checkingForSolution
内部,任何将null
替换为真实值的操作都会提前停止对有效值的搜索。
function findNumber(number) {
function checkingForSolution(current, history) {
if (current == number) return history;
if (current > number) return null;
return checkingForSolution(current + 5, `(${history} + 5)`)
|| checkingForSolution(current * 3, `(${history} * 3)`);
}
return checkingForSolution(1, '1')
|| "sorry could not find algorithm";
}
console.log(findNumber(34));
console.log(findNumber(2));