有人可以帮我解释一下我在这个递归函数上做错了什么吗? 我试图传入一个值,如果该值存在于我的选项列表中,则返回它。如果它不可用,那么我想减去10000并再试一次,直到找到我的匹配值。它几乎正常工作,除非我找到匹配的值,它似乎没有在原始函数调用上更新,也许?不确定。任何帮助将不胜感激。提前谢谢。
var totalCost = 34000,
options = [10000, 0],
recAmt;
if (totalCost >= 30000) {
recAmt = getRecAmt(30000, 1);
console.log(recAmt);
}
function getRecAmt(value, tier) {
console.log('Trying: ' + value + ' for ' + tier);
var i2 = 0,
recAmt = 0;
for (i2 = 0; i2 < options.length; i2 += 1) {
if (value === parseInt(options[i2])) {
recAmt = value;
console.log('Found: ' + recAmt);
}
}
if(recAmt === 0) {
if (tier === 1) {
getRecAmt(value - 10000, tier);
}
} else {
return recAmt;
}
}
目前我的控制台返回
Trying: 30000 for 1
Trying: 20000 for 1
Trying: 10000 for 1
Found: 10000
0
答案 0 :(得分:3)
你没有回复任何东西
if(recAmt === 0) {
if (tier === 1) {
getRecAmt(value - 10000, tier);
}
} else {
return recAmt;
}
需要
if(recAmt === 0) {
if (tier === 1) {
// RETURN STATEMENT HERE
return getRecAmt(value - 10000, tier);
}
} else {
return recAmt;
}
这是一个演示
的片段
var totalCost = 34000,
options = [10000, 0],
recAmt;
if (totalCost >= 30000) {
recAmt = getRecAmt(30000, 1);
console.log(recAmt);
}
function getRecAmt(value, tier) {
console.log('Trying: ' + value + ' for ' + tier);
var i2 = 0,
recAmt = 0;
for (i2 = 0; i2 < options.length; i2 += 1) {
if (value === parseInt(options[i2])) {
recAmt = value;
console.log('Found: ' + recAmt);
}
}
if(recAmt === 0) {
if (tier === 1) {
return getRecAmt(value - 10000, tier);
}
} else {
return recAmt;
}
}
&#13;