0
为什么下面的方法总是返回undefined?事件虽然控制台中的日志显示为真?
javascript中的递归方法总是返回undefined而不是true,
var x = [1,2,3,4,5];
var y = 9;
function addUp (x, y) {
for (var i=0, j=1; j < x.length; j++) {
if (x[i] + x[j] === y) {
console.log("in here result should be true");
var result = true;
break;
}
}
console.log("len", x.length, "result",result);
if ((!result) && (x.length > 2)) {
console.log("recursively calling");
addUp(x.slice(i+1, x.length), y)
} else if(result) {
console.log("in the if why doesn't this return true?")
return true;
} else {
return false;
}
}
addUp(x,y);
卫生署!确实总是错过了,谢谢@shomz!一旦stackoverflow允许我在5分钟内将问题标记为正确。 – climboid
不客气,它发生了。 :)有一件事我学到了,帮助我避免了这个错误:在编写递归函数时,首先编写基本案例(可以是'if(x.length <= 2)return !! result;' )和递归大小写('return addUp ...'),然后处理代码体。 – Shomz