13

我在 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"));

我还有一个函数“更新”,它获取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; 
  }

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

4

6 回答 6

20

“但我想知道一种更好的方法来做到这一点,如果有的话?”

是的,由于您似乎已经拥有原始对象,因此没有理由再次从 Array 中获取它。

  function Update(keyValue, newKey, newValue)
  {
    keyValue.Key = newKey;
    keyValue.Value = newValue; 
  }
于 2012-10-25T13:28:28.483 回答
15

为什么不使用对象1

var dict = { "a": 1, "b": 2, "c": 3 };

然后你可以像这样更新它

dict.a = 23;

或者

dict["a"] = 23;

如果你不想删除2个特定的键,它很简单:

delete dict.a;

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

于 2012-10-25T13:31:24.177 回答
8
function Update(key, value)
{    
    for (var i = 0; i < array.length; i++) {
        if (array[i].Key == key) {
            array[i].Value = value; 
            break;
        }
    }
}
于 2012-10-25T13:32:18.683 回答
3

怎么样;

function keyValue(key, value){
    this.Key = key;
    this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
    this.Key = newKey;
    this.Value = newValue;  
};

array[1].updateTo("xxx", "999");   
于 2012-10-25T13:35:02.803 回答
3

如果要重新分配数组中的元素,可以执行以下操作:

var blah = ['Jan', 'Fed', 'Apr'];

console.log(blah);

function reassign(array, index, newValue) {
    array[index] = newValue;
    return array;
}

reassign(blah, [2], 'Mar');
于 2020-04-08T18:19:01.753 回答
1

所以我有一个需要解决的问题。我有一个带有值的数组对象。如果值 == XI 需要将 X 值更新为 Y 值,我需要更新其中一个值。在这里查看示例,它们都不适合我需要或想要的。我终于想出了一个简单的解决问题的方法,实际上很惊讶它的工作原理。现在通常我喜欢将完整的代码解决方案放入这些答案中,但由于它的复杂性,我不会在这里这样做。如果有人发现他们无法使此解决方案工作或需要更多代码,请告诉我,我将尝试在以后更新此解决方案以提供帮助。在大多数情况下,如果数组对象具有命名值,则此解决方案应该可以工作。

            $scope.model.ticketsArr.forEach(function (Ticket) {
                if (Ticket.AppointmentType == 'CRASH_TECH_SUPPORT') {
                    Ticket.AppointmentType = '360_SUPPORT'
                }
            });

下面的完整示例 _____________________________________________________

   var Students = [
        { ID: 1, FName: "Ajay", LName: "Test1", Age: 20 },
        { ID: 2, FName: "Jack", LName: "Test2", Age: 21 },
        { ID: 3, FName: "John", LName: "Test3", age: 22 },
        { ID: 4, FName: "Steve", LName: "Test4", Age: 22 }
    ]

    Students.forEach(function (Student) {
        if (Student.LName == 'Test1') {
            Student.LName = 'Smith'
        }
        if (Student.LName == 'Test2') {
            Student.LName = 'Black'
        }
    });

    Students.forEach(function (Student) {
        document.write(Student.FName + " " + Student.LName + "<BR>");
    });
于 2020-11-06T16:48:03.747 回答