【问题标题】:I update an array (key,value) object in javascript我在 javascript 中更新了一个数组(键,值)对象
【发布时间】:2013-02-12 00:17:56
【问题描述】:

如何更新数组(键、值)对象?

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

我想将“DistroTotal”更新为一个值。

我试过了

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

谢谢..

【问题讨论】:

  • js对象数组...
  • JavaScript 中的数组具有数字索引(键)。一旦你把一个非数字的“索引”塞进去,它就不再是一个数组了。
  • @NullUserException 我的错,我以为是var arrTotals = [ {DistroTotal: "0.00"}, {coupons: 12}, {invoiceAmount: "14.96"} ]

标签: javascript arrays


【解决方案1】:

因为听起来您正在尝试使用键/值字典。考虑在此处切换为使用对象而不是数组。

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

arrTotals["DistroTotal"] = 2.00;

【讨论】:

    【解决方案2】:

    你缺少了一层嵌套:

    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';
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-31
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多