user1839207
user1839207

Reputation: 87

Javascript Average Array

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

<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>

Upvotes: 5

Views: 14639

Answers (4)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92657

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

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>

Upvotes: 1

AlexStack
AlexStack

Reputation: 17431

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:

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).

By the way, don't forget to put var before 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 scores though that is not the source of this error.

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:

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

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);.

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.

Good luck

Upvotes: 7

Ry-
Ry-

Reputation: 225144

You're not averaging the right way... you get the average from the sum (outside of 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 Number object, 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. scores is undeclared. (Turn strict mode on, please!)

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.
}

Upvotes: 2

Philipp
Philipp

Reputation: 69703

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;

Upvotes: 0

Related Questions