javascript - 使用函数时输出错误
问题描述
我有一个计算价格的函数。当年龄 < 5 时价格 = 0,当年龄 < 15 时价格 = 价格/2,当年龄 > 15 时价格 = 价格 + 价格*0.15。前两个工作正常,但最后一个有问题。例如,当价格输入输入 100 和年龄输入输入 26 时,它给我的答案是 10015。
<script>
function add(x, y) {
return x+y;
}
function Subtract(x, y) {
return x-y;
}
function Divide(x, y) {
return x/y;
}
function Multiply(x, y) {
return x*y;
}
var plusPrice = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
var plusButton = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function updateClickCount() {
document.getElementById("clicks").innerHTML = plusButton();
if (document.getElementById("price").value !== '') {
document.getElementById("input").innerHTML = plusPrice();
}
}
function checkInputs() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if( parseInt(price) < 0 || isNaN(parseInt(price))) {
window.alert("Please insert a valid price");
price = '';
}
if(parseInt(age) > 100 || parseInt(age) < 0 || isNaN(parseInt(age))){
window.alert("Please insert a valid age");
age = '';
}
}
function Calculate() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if (document.getElementById("price").value !== '' && document.getElementById("age").value !== '') {
if (age<5) {
document.getElementById("demo").innerHTML = Subtract(price,price);
} else if (age < 15 && age >= 5) {
document.getElementById("demo").innerHTML = Divide(price,2);
} else {
document.getElementById("demo").innerHTML = add(price,Multiply(price,0.15));
}
} else {
window.alert("Please fill both age and price to calculate the amount you have to pay");
}
}
</script>
<body>
Please enter the price: <br>
<input type="text" id="price"><button onclick="document.getElementById('price').value = ''">Clear input field</button><br><br>
Please enter your age: <br>
<input type="text" id="age"><button onclick="document.getElementById('age').value = ''">Clear input field</button><br><br>
<button onclick="checkInputs(); updateClickCount(); Calculate();">Calculate price</button>
<p id="totalPrice">The total amount you have to pay is: </p><br>
<p id="demo"></p>
<p>Button Clicks: <a id="clicks">0</a></p>
<p>Correct Price Fill Count: <span id="input">0</span></p>
</body>
解决方案
显然,price
是一个字符串。代替
var price = document.getElementById("price").value;
和
var price = parseFloat(document.getElementById("price").value);
该函数已经用于减法和除法,因为运算符-
和/
不能应用于字符串,所以 JS 将它们强制为数字。但是+
, 具有字符串兼容的解释(字符串连接),因此不会发生类型强制。
推荐阅读
- ssis - 如何确保一个 SSIS 任务在并行处理期间首先启动?
- docker - vscode dev 容器环境变量不暴露给 docker-compose
- python - 在 jupyternotebook 的 matplotlib 中显示波斯/阿拉伯字母中断
- c++ - CMAKE 在构建文件中创建一个附加目录
- javascript - 在一组复选框中选择特定的复选框
- javascript - 裸 RN 项目与 Expo Snack 演示的 React Native Flexbox 对齐差异
- python - 如何使用 Pandas 与 groupby 滚动并删除重复项
- android - Android 可访问性:除了宣布 ImageView 的内容描述外,Talkback 还说“不在列表中”
- java - Spring Boot - Java Mail - 无法连接到主机
- android - 无法从 Firebase 数据库读取嵌套数据