【发布时间】:2020-05-14 01:50:59
【问题描述】:
请问,你们能解释一下这个语法/表达式问题吗? 我正在练习,我试图创建一个小费计算器,它会根据账单价值和百分比给我一个小费值。 我不明白为什么变量 finalValues1 中的表达式不起作用。 JSFiddle code result。非常感谢。
document.getElementById('myForm').addEventListener('submit', function (e) {
e.preventDefault();
var bill, tip, percentage, finalValues1, finalValues2;
bill = document.getElementById('bills').value;
if (bill < 50) { // if bill less $50, give tip of 20%.
percentage = .2;
} else if (bill > 50 && bill < 200) { // if bill greater $50 and less than $200, give tip of 15%.
percentage = .15;
} else {
percentage = .1; // if bill greater than $200, give tip of 10%.
}
tip = bill * percentage;
// I want also to display the final value bills plus tip
finalValues1 = bill + tip; // This code does not work, it is concatenating bills and tip.
finalValues2 = bill * 1 + tip; // this code works and it sums bill plus tip. WHY is that?
document.getElementById('demo').innerHTML = "Tip: " + tip + " and total bill plus tip test1: " + finalValues1 + " test2: " + finalValues2 ;
});
【问题讨论】:
-
简单的答案是输入
value返回一个字符串。为了进行数字加法,您需要先将其转换为数字。有很多方法可以转换为数字……都很容易研究。"10" + 1返回字符串"101" -
谢谢。我错过了一些非常简单的东西......元素输入返回一个字符串。我对这个输入 type="number" 感到困惑,它只是为了验证目的。过去几年我可能跳过了这个解释。
标签: javascript syntax operators