Search code examples
javascriptarraysfor-loopdreamweavertypeerror

"Uncaught TypeError: Cannot read property '0' of undefined" javascript array


I am trying to create a project that calculates the sum and average of a series of numbers input into a text field (separated by spaces). So in a single text box a user would enter "1 2 3" and what should happen is that I take the input, separate the numbers by the spaces and put the numbers into an array. Then add the elements in the array up to return the sum and calculate the average as well. However I am stuck on the adding part as I keep getting the error "Uncaught TypeError: Cannot read property '0' of undefined" in console when I run it. I have looked up other people who have had this issue but they seemed to be doing other functions and their fixes don't seem to work for me. I have attached my code in a picture here.

Dreamweaver Code

I have tried things like on line 13 of the javascript I change the Number.numbers[i] to numbers[i].value and that changes the output to NaN. I am quite stuck and would appreciate any help available. Thank you!


Solution

  • To parse your string to number you need to do like this :

    Number(your number).

    So you will have to do like so :

    sum += Number(numbers[i]);