2013-02-12 45 views
3

如何更新数组(键,值)对象?我更新了javascript中的数组(键,值)对象

arrTotals[ 
{DistroTotal: "0.00"}, 
{coupons: 12}, 
{invoiceAmount: "14.96"} 
] 

我想将'DistroTotal'更新为一个值。

我已经试过

for (var key in arrTotals) { 
     if (arrTotals[key] == 'DistroTotal') { 
      arrTotals.splice(key, 2.00); 
     } 
    } 

谢谢..

+0

js对象数组... – Dom 2013-02-12 00:21:09

+0

JavaScript中的数组具有数字索引(键)。只要你推入非数字“索引”,它不再是一个数组。 – NullUserException 2013-02-12 00:21:28

+0

@NullUserException我的错误,我认为它是在说'var arrTotals = [ {DistroTotal:“0.00”}, {coupons:12}, {invoiceAmount:“14.96”} ] – Dom 2013-02-12 00:29:36

回答

6

你错过嵌套的级别:

for (var key in arrTotals[0]) { 

如果您只需将与特定的一个工作,那么做:

arrTotals[0].DistroTotal = '2.00'; 

如果你不知道在哪里与DistroTotal键的对象是,还是有很多人,你的循环是有一点不同:

for (var x = 0; x < arrTotals.length; x++) { 
    if (arrTotals[x].hasOwnProperty('DistroTotal') { 
     arrTotals[x].DistroTotal = '2.00'; 
    } 
} 
7

因为它听起来像你试图用一个键/值字典。考虑切换到使用对象而不是数组。

arrTotals = { 
    DistroTotal: 0.00, 
    coupons: 12, 
    invoiceAmount: "14.96" 
}; 

arrTotals["DistroTotal"] = 2.00; 
相关问题