我的javascript代码有什么问题[重复]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我的javascript代码有什么问题[重复]相关的知识,希望对你有一定的参考价值。
这个问题在这里已有答案:
我不知道为什么它不会工作。它不计算计算总数。它返回数组的总数而不是数组中的总数。
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>
我不知道我做错了什么..我需要帮助。
答案
尝试此解决方案:
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>");
}
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="calculate()">Try it</button>
</body>
</html>
以上是关于我的javascript代码有什么问题[重复]的主要内容,如果未能解决你的问题,请参考以下文章