【问题标题】:js prints as text instead calculatingjs 打印为文本而不是计算
【发布时间】:2016-09-18 10:07:39
【问题描述】:

如果两个if语句中的数量都是从输入元素中取为1 我下面的代码警告 300400 它应该警告 700 作为总和。


function validateCart() {
  var check = false;
  var bill="";
  if (document.getElementById("bbc").checked) {
    check = true;
    var price = 300;
    var quantity = document.getElementById("bbq").value;
    var total = price * quantity;
    bill += total;
  };
  if (document.getElementById("gbc").checked) {
    check = true;
    var price = 400;
    var quantity = document.getElementById("gbq").value;
    var total = price * quantity;
    bill += total;
  };
  if (!check) {
    alert("no item selected");
  } else {
    alert(bill);
  };
};

我不知道我犯了什么错误。

【问题讨论】:

  • 根据给出的代码,输出将是NaN
  • 是的,如果我尝试 var bill = "' ; 我得到 300700 而不是 700 ...等等,让我更新问题
  • 如果你初始化var bill = '',你描述的结果会发生,从那时起你正在做字符串连接。使用var bill = 0;,它应该可以工作。
  • 谢谢它的工作......愚蠢的错误...... -_-

标签: javascript string add


【解决方案1】:

您需要将账单初始化为 0:

function validateCart() {
  var check = false;
  var bill = 0;
  if (document.getElementById("bbc").checked) {
    check = true;
    var price = 300;
    var quantity = document.getElementById("bbq").value;
    var total = price * quantity;
    bill += total;
  };
  if (document.getElementById("gbc").checked) {
    check = true;
    var price = 400;
    var quantity = document.getElementById("gbq").value;
    var total = price * quantity;
    bill += total;
  };
  if (!check) {
    alert("no item selected");
  } else {
    alert(bill);
  };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多