Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Average Array

Tags:

javascript

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>
like image 978
user1839207 Avatar asked Nov 20 '12 15:11

user1839207


People also ask

How do you find the average of an array?

Average is the sum of array elements divided by the number of elements. Examples : Input : arr[] = {1, 2, 3, 4, 5} Output : 3 Sum of the elements is 1+2+3+4+5 = 15 and total number of elements is 5.

Does JavaScript have an average function?

The JavaScript array is first transformed into a collection and then the function is applied to the collection. The avg() method returns the average of all the items in a collection.

How can I calculate average?

Average This is the arithmetic mean, and is calculated by adding a group of numbers and then dividing by the count of those numbers. For example, the average of 2, 3, 3, 5, 7, and 10 is 30 divided by 6, which is 5. Median The middle number of a group of numbers.


2 Answers

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:

  • parseInt()

  • parseFloat()

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

like image 172
AlexStack Avatar answered Nov 11 '22 12:11

AlexStack


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.
}
like image 2
Ry- Avatar answered Nov 11 '22 10:11

Ry-