0
 Array = [ {name:apples, price:3.99, tax:0.20}, 
           {name:oranges, price:1.40, tax:0.15},
           {name:bananas, price:0.99, tax:0.10}, 
         ]

我如何在所有“价格”值(而不是名称,出于性能目的)上运行 toFixed() 以便我想出这个:

 Array = [ {name:apples, price:4, tax:0.20}, 
           {name:oranges, price:1, tax:0.15},
           {name:bananas, price:1, tax:0.10}, 
         ]

我必须通过循环路线吗?

4

3 回答 3

1

只需遍历数组(顺便说一句:永远不要Array用作变量名):

for (var i=0; i<arr.length; i++)
    arr[i].roundedPrice = Math.round(arr[i].price);
于 2012-06-04T18:42:18.340 回答
1

这里:

array.forEach(function ( elem ) {
    elem.price = Math.round( elem.price );
});

现场演示:http: //jsfiddle.net/apSdV/

于 2012-06-04T18:45:49.150 回答
0
for (var ixFruit = 0; ixFruit < fruits.length; ++ixFruit)
    fruits[ixFruit].price = fruits[ixFruit].price.toFixed();

这看起来非常简单,不知道你会如何让它更简单。

于 2012-06-04T18:42:30.440 回答