Javascript 平均数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13476130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:54:14  来源:igfitidea点击:

Javascript Average Array

javascript

提问by user1839207

this is my first post. I am writing a program to get input from four input boxes, find out the sum of these four and finding the average. When i do so I get a NaN error, can someone point where I am going wrong. Thanks

这是我的第一篇文章。我正在编写一个程序来从四个输入框中获取输入,找出这四个的总和并找到平均值。当我这样做时,我得到一个 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>

回答by AlexStack

Welcome to Stackoverflow :) We would be glad to help you while learning our tools better. Just one note about the algorithm: move the average calculation command outside the loop:

欢迎使用 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

I would use parseInt()instead of new Number()because new Number()creates an object while parseInt()gives you the actual literal value as a result. (better performance).

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

By the way, don't forget to put varbefore every variable definition unless you want them to be accessed globaly (bad idea). You did a good job with all variables except scores. The definition should be var scoresthough that is not the source of this error.

顺便说一句,var除非您希望全局访问它们(坏主意),否则不要忘记在每个变量定义之前放置。除了scores. 定义应该是var scores虽然这不是此错误的根源。

Another point: you can check if the result of parseInt()using isNaN()function. If your numbers can have decimal points, you can use parseFloat()also:

另一点:您可以检查parseInt()使用isNaN()函数的结果。如果您的数字可以有小数点,您也可以使用parseFloat()

The result of both functions is NaN (not a number) if the conversion from string to number fails.

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

And finally, I think it is a good idea that you defined the array with a specified length. It improves the readability of your code. However it is not necessary in Javascript as it automatically increases/decreases the length of the array at runtime so you don't have to decide in advance how long it should be. It can be a good thing or a bad thing depending how you use it. But in general you can use var myarr=[];instead of var myarr= new Array();. However when you want to hint the other developers what's going on, you may specify the array length as well: var myarr=new Array(4);.

最后,我认为您定义具有指定长度的数组是个好主意。它提高了代码的可读性。然而,它在 Javascript 中不是必需的,因为它会在运行时自动增加/减少数组的长度,因此您不必提前决定它应该有多长。它可能是好事也可能是坏事,这取决于您如何使用它。但一般来说,您可以使用var myarr=[];代替var myarr= new Array();. 然而,当你想暗示其他开发人员这是怎么回事,你可以指定数组的长度也:var myarr=new Array(4);

And final point for using Stackoverflow: please accept the best answer and "up vote" the other useful answers. This way you will get a score and other people as well.

使用 Stackoverflow 的最后一点:请接受最佳答案并“投票”其他有用的答案。这样你会得到一个分数,其他人也会得到。

Good luck

祝你好运

回答by Ry-

You're not averaging the right way... you get the average from the sum (outsideof the loop) divided by the number of marks.

你没有以正确的方式求平均值......你从总和(循环)除以分数的数量得到平均值。

Also:

还:

  1. Don't use new Array(4). Predefining array lengths in JavaScript is unnecessary (and can hurt readability and performance).
  2. Don't use new Number(), ever. This creates a Numberobject, which is a terrible thing that will wreak havoc at some point in time. Use Number(yourString)to cast.
  3. I highly recommend you put semicolons at the end of your statements.
  4. scoresis undeclared. (Turn strict mode on, please!)
  1. 不要使用new Array(4). 在 JavaScript 中预定义数组长度是不必要的(并且会损害可读性和性能)。
  2. new Number()永远不要使用。这会创建一个Numberobject,这是一件可怕的事情,会在某个时间点造成严重破坏。使用Number(yourString)到演员。
  3. 我强烈建议您在语句的末尾加上分号。
  4. scores未申报。(请打开严格模式!)

Anyway, here's what that could look like:

无论如何,这可能是这样的:

function average(form) {
    var scores = [ // Array literal!
        Number(form.mark1.value), // You could also use a leading +
        Number(form.mark2.value),
        Number(form.mark3.value),
        Number(form.mark4.value)
    ];

    var sum = 0;

    for(var i = 0; i < scores.length; i++) {
        sum += scores[i];
    }

    var average = sum / scores.length;

    // etc.
}

回答by Philipp

The way you build your scores array is needlessly complex. You can just do this:

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

scores [0] = form.mark1.value;
scores [1] = form.mark2.value;
scores [2] = form.mark3.value;
scores [3] = form.mark4.value;

Then you have an error in your average calculation. The correct way to calculate an average is by summing up all the values and then divide them through the number of values once.

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

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

回答by Kamil Kie?czewski

To find average first calc sum (e.g. by reduce), then divide - thats all

要找到平均第一个计算总和(例如通过reduce),然后除以 - 这就是全部

var Sum = scores.reduce((a,b)=> a+b);    // calculate sum
var average = Sum/scores.length;         // divide by number of elements

<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 = scores.reduce((a,b)=> a+b);
var average = Sum/scores.length;

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>