var array = [];
getNum();
document.write(array);
document.write("<br>Sum: " + sum(array));
//Function to Sum Array
function sum(params){
var total = 0 ;
for (i = 0; i < params.length; i++){
total += params[i];
}
return total;
}
//Function to get Numbers in Array
function getNum(){
var count = 0;
alert("Please enter 5 numbers");
while(count < 5) {
array[count] = prompt("Number " + (count + 1));
count++;
}
}
Current Output
5,4,3,2,1
Sum: 054321
What I want
5,4,3,2,1
Sum: 15
I'm trying to make a program where the user adds numbers to an Array and the program calculates different things about those numbers.
When I call sum(array); with a preset array such as var array = [5,4,3,2,1]; The summing works fine and outputs 15 as expected.
However instead of having a preset array, when I include the function to get the set of numbers for the Array, the summation the output is 054321.
I want to do the array calculations manually for my own understandings sake, rather than using reduce();
What am I doing wrong?
prompt()to anintbefore you add it to the array.