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 amounts 3, 1, and 5, then instead of totalAmt
being 9, i get 0315
. So I think its adding the amounts together as strings instead of integars.
How do I fix this?
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 amounts 3, 1, and 5, then instead of totalAmt
being 9, i get 0315
. So I think its adding the amounts together as strings instead of integars.
How do I fix this?
Share Improve this question asked Sep 13, 2009 at 1:49 AliAli 267k269 gold badges592 silver badges786 bronze badges2 Answers
Reset to default 11order.amount
is a string, and if one of the operands of the + operator is a string, a concatenation is done instead of a sum.
You should convert it to 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
}
You could alternatively use:
totalAmt = totalAmt + (+order.amount);
totalAmt = totalAmt + Number(order.amount);
totalAmt = totalAmt + parseFloat(order.amount);
// etc...
Also you are using a for..in loop to iterate over orders
, if orders
is an array, you should use a normal for loop:
for (var i = 0; i<orders.length; i++) {
//...
}
That is because the for...in statement is intended to be used for iterate over object properties, for arrays it may be tempting to use it, because seems to work, but it's not remended since it will iterate over the object properties, and if you have extended the Array.prototype, those properties will be also iterated in addition to the numeric indexes.
Another reason to avoid it is because the order of iteration used by this statement is arbitrary, and iterating over an array may not visit elements in numeric order, and also it seems to be much more slower than a simple for loop.
If iteration order is not important, I personally like iterating backwards:
var i = orders.length;
while (i--) {
//...
}
Use the parseFloat()
or parseInt()
functions to convert the string to the appropriate type.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745305461a4621681.html
评论列表(0条)