Javascript平均数组

use*_*207 5 javascript

这是我的第一篇文章.我正在编写一个程序来从四个输入框中获取输入,找出这四个输入框的总和并找到平均值.当我这样做时,我得到一个NaN错误,有人指出我错了.谢谢

<html>
<head>
<title> Average marks </title>

<script type = "text/javascript">

function average(form)
{

scores = new Array(4)

scores [0] = form.mark1.value
scores [0] = new Number(scores[0])
scores [1] = form.mark2.value
scores [1] = new Number(scores[1])
scores [2] = form.mark3.value
scores [2] = new Number(scores[2])
scores [3] = form.mark4.value
scores [3] = new Number(scores[3])


var Sum = 0
var average

for(var x = 0; x < scores.length; x ++)
{
Sum = Sum + scores[x]
average = Sum / scores[x]
}



document.write("The sum of the marks is equal to " + Sum + "<br>")
document.write("The average of these marks is equal to " + average + "<br>")


}

</script>


</head>

<body>

<form>
Enter the first mark : <input type = "text" name="mark1"> <br>
Enter the second mark : <input type = "text" name="mark2"> <br>
Enter the third mark : <input type = "text" name="mark3"> <br>
Enter the fourth mark : <input type = "text" name="mark4"> <br>

<input type = "submit" value = "submit" onclick="average(this.form)">
</form>


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

Ale*_*ack 7

欢迎来到Stackoverflow :)我们很乐意帮助您更好地学习我们的工具.关于算法的一点注意事项:在循环外移动平均计算命令:

for(var x = 0; x < scores.length; x ++)
{
  Sum = Sum + scores[x];  //or Sum += scores[x];
}

average = Sum / scores.length;  //length of the array scores is in scores.length
Run Code Online (Sandbox Code Playgroud)

我会使用parseInt()而不是new Number()因为new Number()创建一个对象,同时parseInt()为您提供实际的文字值.(更好的性能).

顺便说一句,不要忘记var在每个变量定义之前放置,除非你想要它们被全局访问(坏主意).你做了很好的所有变量,除了scores.定义应该是var scores虽然这不是此错误的来源.

还有一点:你可以检查一下parseInt()使用isNaN()功能的结果.如果您的数字可以有小数点,您还可以使用parseFloat():

如果从字符串到数字的转换失败,则两个函数的结果都是NaN(不是数字).

最后,我认为您定义具有指定长度的数组是个好主意.它提高了代码的可读性.但是在Javascript中没有必要,因为它会在运行时自动增加/减少数组的长度,因此您不必事先决定应该多长时间.根据您的使用方式,这可能是好事还是坏事.但一般来说,你可以使用var myarr=[];而不是var myarr= new Array();.但是,当您想要提示其他开发人员正在进行的操作时,您也可以指定数组长度:var myarr=new Array(4);.

使用Stackoverflow的最后一点:请接受最佳答案和"向上投票"其他有用的答案.这样你就可以得到一个分数和其他人.

祝好运

  • +1综合答案,但是:w3schools是一个不好的参考.([为什么?](http://w3fools.com/))使用适当的参考资料,例如[Mozilla Developer Network](https://developer.mozilla.org/en/)或[Sitepoint](http: //www.sitepoint.com/). (2认同)

Phi*_*ipp 0

构建分数数组的方式不必要地复杂。你可以这样做:

scores [0] = form.mark1.value;
scores [1] = form.mark2.value;
scores [2] = form.mark3.value;
scores [3] = form.mark4.value;
Run Code Online (Sandbox Code Playgroud)

那么你的平均计算就会出现错误。计算平均值的正确方法是将所有值相加,然后将它们除以值的数量一次。

for(var x = 0; x < scores.length; x ++)
{
    Sum = Sum + scores[x];
}
average = Sum / scores.length;
Run Code Online (Sandbox Code Playgroud)