在学习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]
答案 0 :(得分:3)
您不能分配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);
答案 1 :(得分:0)
console.log返回未定义。有关更多信息,请参见下面链接的规格。
此外,在您的示例中,您不必将结果存储到变量tip1,tip2,tip3中。
相反,您可以直接在console.log中调用paidAmount:
console.log(paidAmount(124), paidAmount(48), paidAmount(268));
答案 2 :(得分:0)
[console.log(tip1),console.log(tip2),...]
是错误,但是您可以尝试另一种方法:
function paidAmount(bill) {
var tipTotal = [] ;
var tipPercent ;
for (value of bill) {
tipPercent = (value < 50 ) ? 0.20 : ( ( value >= 50 && value <= 200) ? 0.15 : 0.10 ) ;
tipTotal.push( value * tipPercent ) ;
}
return tipTotal ;
}
console.log( paidAmount([124, 48, 268]) );