Javascript Problem

jhayx7

Platinum Member
Oct 1, 2005
2,226
0
0
Ok, I might have been staring at this for too long and it is just a glaring problem but I have an array with cash values that I am trying to add using a for loop. My array is named "amount" and here is the code. It does not work for some reason and I can not figure out why. This is the first time I have tried to sum array values.

 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,701
4,661
75
Did you mean "i < amount.length"?
 

jhayx7

Platinum Member
Oct 1, 2005
2,226
0
0
Originally posted by: Ken_g6
Did you mean "i < amount.length"?

No, I want the sum of the numbers in the array. Say that my array is:

var amount = newArray("20", "30", "15", "5");

I want the output of the total variable to be 70 (20+30+15+5), not 4. See what I'm saying? Hope that makes sense.. been writing script since 8 am and have a killer headache.
 

mlm

Senior member
Feb 19, 2006
933
0
0
I haven't done much with JS, only Java, but you want something more like the attached. I'm not sure if JS has a += operator, but it's essentially what you want.

Here's a w3schools example that looks similar to what you're doing.
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
for (var i=0; i<amount; i++)
literally works out to
for (var i=0; i<[Object array]; i++)

That's garbage.

This is your code with that issue fixed:

function amountTotal() {
var total;
total = 0;
i added .length on the line below
for (var i=0; i < amount.length; i++) { please post what values you think "i" will have after each iteration
total++; please post what values you think "total" will have after each iteration
}
return total;
}
 

jhayx7

Platinum Member
Oct 1, 2005
2,226
0
0
Originally posted by: mlm
I haven't done much with JS, only Java, but you want something more like the attached. I'm not sure if JS has a += operator, but it's essentially what you want.

Here's a w3schools example that looks similar to what you're doing.

That's close! The script joins the numbers in the array together but does not add them together. The result is 0721 not 10 :(

 

mlm

Senior member
Feb 19, 2006
933
0
0
Try taking out the double quotes when you're declaring the elements. When you do that, that forces them to be strings :)
 

jhayx7

Platinum Member
Oct 1, 2005
2,226
0
0
Woohoo! That did it guys! For some reason, the Tryit Editor didn't want to add the values together but when I put the code into my file, it worked. Except for I can't put it in a function and return the value... I have to leave it out of a function.. Will figure that out later. Thanks a million for the help.

Final working code: