值显示在一起而不是新值

Den*_*tor 0 javascript

我今天在大学做了一个练习,它是一个JavaScript程序来计算测试中学生的平均分数.

这是我的代码:

<!DOCtype html>

<html>
<head>
<title>While loop</title>
</head>
<body>
<script>

    //The total score of all pupils
    var total = 0;
    //The number of scores
    var count = 1;

    while (count <= 10) {
        grade = prompt("Insert the grade:");
        total = total + grade;
        count++;
        }

    var average = +total / 10;
    document.write("The average is " + average);

</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我输入的值是10-100,上升10到10.所以我把10个值"10,20,30,40,50,60,70,80,90,100"放进去,而不是得到平均值,我得到了所有这些值并排.

我究竟做错了什么?

tym*_*eJV 5

grade = prompt("Insert the grade:");是问题.提示将您的输入作为字符串,在JS中,添加两个字符串只是连接值.所以解析你的输入:

grade = +prompt("Insert the grade:"); //+ is shorthand for casting to a number
Run Code Online (Sandbox Code Playgroud)

或者使用 parseInt

grade = prompt("Insert the grade:");
var numberGrade = parseInt(grade);
Run Code Online (Sandbox Code Playgroud)

仅供参考 - 你要添加的所有数字必须是整数 - 否则它最终会再次作为字符串,例如:

10 + 10; //20
10 + "10" //1010
10 + 10 + "10" //2010
Run Code Online (Sandbox Code Playgroud)