Click here to Skip to main content
15,912,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm appealing for an assistance in developing JavaScript program that asks a user to input integers(say 10 integers) , store them in an array called nums(array of 10 integers), then pass this array to a function called add which adds all the array values and returns the correct answer. My attempts have bore no fruits...I trust someone will help me out. If there are other easier approaches, I shall very much appreciate. Thank you!


What I have tried:

<html>
<head>
<script>
function Add(d){// array reference received
var j,sum;
sum=0;
for(j=0;j<10;j++){
sum=sum+parselnt(d[j]);
}
return sum
}
</script>
</head>
<body bgcolor="aqua">
<script>
var num=new Array(10);
var i;
for(i=0;i<10;i++){
num[i]=prompt("Enter value at "+i);
}
alert("The sum of the ten numbers is "+Add(num));//call and pass array name
</script>
</body>
</html>
Posted
Updated 1-Apr-18 5:28am
v2

syntax error :
sum=sum+parselnt(d[j]);
Correction: parseInt
JavaScript parseInt() Function[^]
 
Share this answer
 
Comments
Member 13226075 1-Apr-18 11:20am    
Many thanks.
Hi,
I altered your function so that it could take any number of elements in an array and summarizes it.

JavaScript
<html>
<head>
  <script>
  function Add(d){// array reference received
    var sum=0;
    d.forEach(item=>{
	    sum+=parseInt(item);
    });
    return sum
  }
  </script>
</head>
<body bgcolor="aqua">
<script>
var num=[];
for(i=0;i<10;i++){
  num.push(prompt("Enter value at "+i));
}
alert("The sum of the ten numbers is " + Add(num));//call and pass array name
</script>
</body>
</html>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900