US Business Directory - Debt Consolidation - Reference 2007 - Find jobs - Debt Consolidation

PDA

View Full Version : adding the values of an array


borojim
Feb 17th 2009, 6:48 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...)

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

Many Thanks

Jimmy

dimitar christoff
Feb 17th 2009, 7:10 am
try + parseInt(candidateArray[i]) or parseFloat() if necessary

even though you enter numbers, it treats them as string as they have arrived from a user input that can return anything...

gnp
Feb 18th 2009, 9:09 am
Additionally to what dimitar said,

i see that you use the parseFloat in a couple of places but without assigning the returning value anywhere..

the parseFloat will not alter the variable that you pass it number as text.. it will return that value to be assigned somewhere..

so


parseFloat(candidateNumb);
//should be
candidateNumb = parseFloat(candidateNumb);

//AND

parseFloat(candidateArray[i].value);
//should be
candidateArray[i].value = parseFloat(candidateArray[i].value);


making these two changes would make your code work as expected because you would now be dealing with numbers..

hth