-2

I tried to iterate through the array and print the sum. But the output am getting is elements of the array.

 <p id="ans"></p>

    <script>
      var text = "the mean is ";
      function mean() {
        var sum = 0;
        var input = document.getElementsByName("values");
        for (var i = 0; i < input.length; i++) {
          sum += input[i].value;
          text = text + sum;
        }

        document.getElementById("ans").innerHTML = text;
      }
    </script>
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
  • 1
    try using `.reduce()` higher order function. There should be plenty of examples for getting the sum of the array, which then you could divide by the array length to get the mean :) – Sinan Yaman Apr 23 '22 at 20:28
  • You are adding numbers multiple times to the string. They thus will be concatenated instead of numerically added. Make sure you sum to a numeric variable and only add it to the string when the math work is done. – mousetail Apr 23 '22 at 20:29

1 Answers1

0

Parse the string values into integers and then sum it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt This is because in javascript if you adding a number to a string it will be casted to a string. For example:

0 + '1' + '2' // 012

But with parse int:

0 + parseInt('1') + parseInt('2') // 3

Or you can cast to int with a simple plus also:

0 + (+'1') + (+'2') // 3
  • This should help to you to fix your code. Just modify the line: sum += parseInt(input[i].value); – Zsombor Szende Apr 23 '22 at 20:34
  • When using `parseInt` [always specify an radix](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#parameters) – pilchard Apr 23 '22 at 20:35