Adult ADHD - Find jobs - Web Hosting - Premium wordpress themes - Bad Credit Loans

PDA

View Full Version : adding Array Values to find average/make a percentile graph etc


borojim
Feb 17th 2009, 6:53 am
Hi I have this script:

<script type="text/javascript">
//request the number of candidates
var candidateNumb = prompt("Please Enter How many Candidates there are", "");
var candidateArray = new Array();
var totalVotes = 0;
parseFloat(candidateNumb);

//request the votes given to the candidates in order
for (i=0; i<=(candidateNumb-1); i++)
{
candidateArray[i] = prompt("Please Enter the number of votes for Candidate " + (i + 1), "");
parseFloat(candidateArray[i].value);

//display what has been given so far....
document.write("CandidateArray[" + i + "] is " + candidateArray[i] + "<br />");
document.write("<br />The total Votes so far is " + totalVotes);
}
</script>

where its says:
//display what has been given so far....
document.write("CandidateArray[" + i + "] is " + candidateArray[i] + "<br />");
document.write("<br />The total Votes so far is " + totalVotes);

is not part of the script I have used that as a sort of debug, so that I can see that the values are being passed along nicely.

now when I change that bit of code to:

//display what has been given so far....
totalVotes = (totalsVotes + candidateArray[i]);

document.write("CandidateArray[" + i + "] is " + candidateArray[i] + "<br />");
document.write("<br />The total Votes so far is " + totalVotes);

What I am hoping to get is a value of the entire Array added together, but what actually happens is I get a string of the values concacencatencentacatred.... Joined together!
(sorry I forget to stop spelling it sometimes...)

Also dont worry about validation I have that sorted and have removed it for simplicity for the time being.

Once I have a total of the array values I can carry one but...

Please can someone let me know what I am doing wrong???

Many Thanks

Jimmy

bprashanth.gi
Feb 17th 2009, 8:15 am
Hi Jimmy,

Use parse function when adding with totalVotes. It solves the problem.
<script type="text/javascript">
//request the number of candidates
var candidateNumb = prompt("Please Enter How many Candidates there are", "");
var candidateArray = new Array();
var totalVotes = 0;
parseFloat(candidateNumb);

//request the votes given to the candidates in order
for (i=0; i<=(candidateNumb-1); i++)
{
candidateArray[i] = prompt("Please Enter the number of votes for Candidate " + (i + 1), "");
//parseInt(candidateArray[i].value);
totalVotes = totalVotes + parseInt(candidateArray[i]);
//display what has been given so far....
document.write("<br />CandidateArray[" + i + "] is " + candidateArray[i] + "<br />");
document.write("The total Votes so far is " + totalVotes);
}
</script>