javascript中的递归方法总是返回undefined而不是true,
为什么下面的方法总是返回undefined?事件,但控制台中的日志显示为true?javascript中的递归方法总是返回undefined而不是true,,javascript,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;
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);
var x=[1,2,3,4,5];
变量y=9;
函数加总(x,y){
对于(变量i=0,j=1;j2)){
log(“递归调用”);
加总(x.slice(i+1,x.length),y)
}否则,如果(结果){
log(“在if中,为什么不返回true?”)
返回true;
}否则{
返回false;
}
}
加总(x,y);
问题出在您的第一个if
语句中
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;
}
您将看到,if((!result)&&(x.length>2)){
没有返回任何内容。因此,如果找到此匹配项,将不会执行下面两个else语句
您应该在第一个if语句中提供一个return语句,或者在方法的末尾放置一个最终的return语句。您可能希望返回递归调用的结果:
return addUp(x.slice(i+1, x.length), y)
而不仅仅是:
addUp(x.slice(i+1, x.length), y)
doh!真的完全没有注意到,谢谢@shomz!只要stackoverflow允许,我会在5分钟内将问题标记为正确。不客气,它会发生。:)我学到的一件事帮助我避免了这个错误:在编写递归函数时,从编写基本情况开始(可能类似于
if(x.length