[英]Ternary Operator not yielding expected result
In JavaScript: I have a ternary operator being instructed to return a tip percentage of %15 if the bill amount is between $50-300, otherwise being instructed to reuturn a tip percentage of %20.在 JavaScript 中:如果账单金额在 50-300 美元之间,我有一个三元运算符被指示返回 %15 的小费百分比,否则被指示返回 %20 的小费百分比。 On a bill amount of $275, it is still yielding %20.
在 275 美元的账单金额上,它仍然产生 20% 的收益。 I have looked at many examples of functioning ternary operators and my code seems to be properly worded and yet the result comes out incorrect every time.
我查看了许多功能三元运算符的示例,我的代码似乎措辞正确,但每次结果都不正确。 In what way am I failing?
我在什么方面失败了?
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
let bill;
let tip_percentage = bill >= 50 && bill <= 300 ? 0.15 : 0.2;
bill = bill_1;
console.log(`The first table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
bill = bill_2;
console.log(`The second table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
bill = bill_3;
console.log(`The third table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
As @Matt said in the comment, tip_percentage
is not a function and must be calculated each time you change the bill amount.正如@Matt 在评论中所说,
tip_percentage
不是 function,每次更改账单金额时都必须计算。
Try this:尝试这个:
const bill_1 = 40; const bill_2 = 275; const bill_3 = 430; function getTip(bill) { var tip = (bill >= 50 && bill <= 300)? 0.15: 0.2; return tip; } alert(`Bill one's tip: ${getTip(bill_1)}`); alert(`Bill two's tip: ${getTip(bill_2)}`); alert(`Bill two's tip: ${getTip(bill_3)}`);
tip_percentage
is already calculated. tip_percentage
已经计算过了。
If you want to make different result values depending on the variable, make them in the form of functions.如果你想根据变量做出不同的结果值,可以用函数的形式来制作。
const bill_1 = 40; const bill_2 = 275; const bill_3 = 430; const tip_percentage = (bill) => (bill >= 50 && bill <= 300? 0.15: 0.2); const printTipResult = (bill) => { console.log(`The third table's bill came out to $${bill}. After the tip of ${tip_percentage(bill)}% (equalling: $${bill * tip_percentage(bill)}) was added, the final amount owed is: $${bill * tip_percentage(bill) + bill}`); }; printTipResult(bill_1); printTipResult(bill_2); printTipResult(bill_3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.