Strange javascript adding issue

I have this code:

var totalAmt=0;
for (i in orders)
{
   order=orders[i];
   if (order.status !='Cancelled')
        totalAmt=totalAmt + order.amount;
}

But if I have 3 orders with the sums of 3, 1 and 5, then instead of totalAmt9, I get 0315. Therefore, I think it adds the sums together as strings instead of integers.

How to fix it?

+1
source share
2 answers

order.amount is a string, and if one of the operands of the + operator is a string, concatenation is performed instead of the sum.

You must convert it to a number, for example, using the unary plus operator:

var totalAmt = 0, i, order; // declaring the loop variables
for (var i in orders) {
   order = orders[i];
   if (order.status !='Cancelled')
        totalAmt += +order.amount; // unary plus to convert to number
}

Alternatively you can use:

totalAmt = totalAmt + (+order.amount);
totalAmt = totalAmt + Number(order.amount);
totalAmt = totalAmt + parseFloat(order.amount);
// etc...

Also you use for..in loop to iterate over orders, if orders- an array, you should use a regular loop:

for (var i = 0; i<orders.length; i++) {
  //...
}

, for...in , , , , , , Array.prototype, .

- , , , , , , , , .

, :

var i = orders.length;
while (i--) {
   //...
}
+11

parseFloat() parseInt() .

+1

All Articles