如何更新数组值javascript?

Tom*_*der 7 javascript jquery

我在javacsript中有一个由3个keyValue构造函数对象组成的数组:

  function keyValue(key, value){
    this.Key = key;
    this.Value = value;
  };

  var array = [];
  array.push(new keyValue("a","1"),new keyValue("b","2"),new keyValue("c","3"));
Run Code Online (Sandbox Code Playgroud)

我还有一个函数'Update',它接受keyValue object as parameter并更新数组中该对象的值:

  function Update(keyValue, newKey, newValue)
  {
    //Now my question comes here, i got keyValue object here which i have to 
    //update in the array i know 1 way to do this 

    var index = array.indexOf(keyValue);
    array[index].Key = newKey;
    array[index].Value = newValue; 
  }
Run Code Online (Sandbox Code Playgroud)

但是如果有的话,我想要一个更好的方法来做到这一点.

I H*_*azy 14

"但我想知道更好的方法,如果有的话?"

是的,因为你似乎已经有了原始对象,所以没有理由再从Array中获取它.

  function Update(keyValue, newKey, newValue)
  {
    keyValue.Key = newKey;
    keyValue.Value = newValue; 
  }
Run Code Online (Sandbox Code Playgroud)


I a*_*ica 11

为什么不使用对象1

var dict = { "a": 1, "b": 2, "c": 3 };
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样更新它

dict.a = 23;
Run Code Online (Sandbox Code Playgroud)

要么

dict["a"] = 23;
Run Code Online (Sandbox Code Playgroud)

如果你不想删除2一个特定的键,它就像这样简单:

delete dict.a;
Run Code Online (Sandbox Code Playgroud)

1 有关键/值对,请参阅Javascript中的对象与数组.
2delete操作员.


Jer*_*rry 6

function Update(key, value)
{    
    for (var i = 0; i < array.length; i++) {
        if (array[i].Key == key) {
            array[i].Value = value; 
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)