2013-02-12 49 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; 
相關問題