简体   繁体   中英

Javascript adding multiple products

I am stuck trying to figure out the correct syntax for coming up with a number which is the sum of several products. Like this:

var sum = (a*b) + (c*d) + (e*f)

Please help before i pull out all my hair. There's not much left....

Problem was solved! Thanks to bvx89 Chandranshu for putting me on the right track:

The variables are either undefined or strings. If you've received the numbers from input fields they are probably strings, and you should use parseInt(x) on each one. – bvx89 Nov 19 at 23:21

Thanks, bvx89! that was it. a few of the variables came from , and I didn't realize that they were considered strings. I got it working now. Thaks a lot for your help. I can finally get som sleep tonight. – Schpenn Nov 19 at 23:28

Well, you can store the products in an array, and then sum all the values of the array.

Something like

var products = [];
var total = 0;
products.push(a * b);
products.push(c * d);
products.push(e * f);

for (var i = 0; i < products.length; i++) {

    total = total + products[i];
}
alert(total);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM