• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Javascript Problem

jhayx7

Platinum Member
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.

 
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.
 
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.
 
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;
}
 
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 🙁

 
Try taking out the double quotes when you're declaring the elements. When you do that, that forces them to be strings 🙂
 
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:

 
Back
Top