我在 javascript 中更新了一个数组 (key,value) 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14823413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:02:21  来源:igfitidea点击:

I update an array (key,value) object in javascript

javascriptarrays

提问by Ravi Ram

How can I update an array (key,value) object?

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

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

I want to update the 'DistroTotal' to a value.

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

I have tried

我试过了

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

Thanks ..

谢谢 ..

回答by Dan Saltmer

Since it sounds like you are trying to use a key/value dictionary. Consider switching to using an object instead of an array here.

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

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

arrTotals["DistroTotal"] = 2.00;

回答by Explosion Pills

You're missing a level of nesting:

您缺少嵌套级别:

for (var key in arrTotals[0]) {

If you only need to work with that specific one, then just do:

如果您只需要使用那个特定的,那么只需执行以下操作:

arrTotals[0].DistroTotal = '2.00';

If you don't know where the object with the DistroTotalkey is, or there are many of them, your loop is a bit different:

如果你不知道带DistroTotal键的对象在哪里,或者有很多对象,你的循环有点不同:

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