首页 > 解决方案 > 使用函数时输出错误

问题描述

我有一个计算价格的函数。当年龄 < 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>

标签: javascript

解决方案


显然,price是一个字符串。代替

    var price = document.getElementById("price").value;

    var price = parseFloat(document.getElementById("price").value);

该函数已经用于减法和除法,因为运算符-/不能应用于字符串,所以 JS 将它们强制为数字。但是+, 具有字符串兼容的解释(字符串连接),因此不会发生类型强制。


推荐阅读