我的javascript代码有什么问题

时间:2017-12-28 09:16:54

标签: javascript html

我不知道为什么它不起作用。它不会计算总计。它返回数组的总数而不是数组中的总数。

function calculate() {
  var num = prompt("How many number : ");
  var number = [];
  var i = 0,
    count, count1, total, total1;

  while (i < num) {
    number.push(prompt("Enter a number :"));

    if (number[i] > 5) {
      count = count + 1;
      total = total + number[i];
    } else if (number[i] <= 5) {
      count1 = count1 + 1;
      total1 = total1 + number[i];
    }
    i++;

  }

  document.write("For count >5 ", count);
  document.write("For total >5 ", total);
  document.write("For count <=5 ", count1);
  document.write("For total >5 ", total1);
}
<html>

<body>
  <p>Click the button to demonstrate the prompt box.</p>
  <button onclick="calculate()">Try it</button>
</body>

</html>

我不知道我做错了什么..我需要帮助。

1 个答案:

答案 0 :(得分:0)

试试这个解决方案:

&#13;
&#13;
function calculate() {
  var num = prompt("How many number : ");
  var number = [];
  var i = 0,
    count=0, count1=0, total=0, total1=0;

  while (i < num) {
    number.push(prompt("Enter a number :"));

    if (parseInt(number[i]) > 5) {
      count++;
      total = total + parseInt(number[i]);
    } else if (parseInt(number[i]) <= 5) {
      count1++;
      total1 = total1 + parseInt(number[i]);
    }
    i++;

  }

  document.write("For count >5 is ", count,"</br>");
  document.write("For total >5 is  ", total,"</br>");
  document.write("For count <=5 is " , count1,"</br>");
  document.write("For total >5 is ", total1,"</br>");
}
&#13;
<html>

<body>
  <p>Click the button to demonstrate the prompt box.</p>
  <button onclick="calculate()">Try it</button>
</body>

</html>
&#13;
&#13;
&#13;