在学习JavaScript并尝试解决挑战性问题时,我的代码不断输出“未定义的值”。

我的代码:

function paidAmount(bill){
var tipPercent
if (bill < 50){
    tipPercent = 0.20;
}
else if (bill >= 50 && bill <=200){
    tipPercent = 0.15;
}
else{
    tipPercent = 0.10;
}
return bill * tipPercent;
}

var tip1 = console.log(paidAmount(124));
var tip2 = console.log(paidAmount(48));
var tip3 = console.log(paidAmount(268));

var tipTotal = [tip1, tip2, tip3];

console.log(tipTotal);


输出:

18.599999999999998
9.600000000000001
26.8
(3) [undefined, undefined, undefined]

最佳答案

您不能分配console.log内部的值。将它们分开



function paidAmount(bill){
var tipPercent
if (bill < 50){
    tipPercent = 0.20;
}
else if (bill >= 50 && bill <=200){
    tipPercent = 0.15;
}
else{
    tipPercent = 0.10;
}
return bill * tipPercent;
}


var tip1 = paidAmount(124);
var tip2 = paidAmount(48);
var tip3 = paidAmount(268);
console.log(paidAmount(124));
console.log(paidAmount(268));
console.log(paidAmount(48));
var tipTotal = [tip1, tip2, tip3];

console.log(tipTotal);

09-11 07:12