domingo, 28 de septiembre de 2014

JavaScript: create a function with an array as a parameter (calculating the mean of n number of students' scores)

The function calculates the mean of a class with any number of students. At first this was difficult to me cause I'm a novice in the use of arrays. Even when my score was 10/10, I had to re-read the program to understand what I did :p.
  1. var class1 = [75, 53, 92, 100, 24, 55, 86,
  2.               85, 43, 55, 84, 82, 99, 51];
  3.               
  4. var class2 = [54, 92, 72, 65, 66, 
  5.               83, 44, 81, 88, 78];

  6. function sum(array) {
  7.   var sum = 0;
  8.   for (i = 0; i < array.length; i++) {
  9.     sum += array[i]
  10.   }
  11.   return sum;
  12. }

  13. function mean(array) {
  14.   return sum(array) / array.length;
  15. }

  16. var mean1 = mean(class1);
  17. var mean2 = mean(class2);

  18. console.log('Class 1 mean: ' + Math.round(mean1));
  19. console.log('Class 2 mean: ' + Math.round(mean2));
Class 1 mean 70
Class 2 mean 72

The program above was made in codeavengers.com 


Español: El programa arriba escrito calcula la media de n estudiantes en una clase cualquiera. La amplitud no es fija, sólo depende del array. Fue hecho en codeavengers en el curso de javascript nivel 2.

No hay comentarios:

Publicar un comentario