更新关联数组中每个项的值

时间:2016-08-10 08:39:16

标签: javascript arrays

我有一个JavaScript关联数组,比如说:

var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";

如何更新此数组中每个项的值,以便输出

myArray["id1"] = "newValue";
myArray["id2"] = "newValue";
myArray["id3"] = "newValue";

2 个答案:

答案 0 :(得分:4)

使用 Object.keys() 获取所有属性名称数组,然后使用 Array#forEach 方法迭代更新属性值。

var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";

Object.keys(myArray).forEach(function(k) {
  myArray[k] = 'newVal';
});

console.log(myArray);

使用while循环的速度更快。

var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";

var names = Object.keys(myArray),
  i = names.length;

while (i--) {
  myArray[names[i]] = 'newVal';
};

console.log(myArray);

答案 1 :(得分:2)

  • 用于循环
  • 始终建议使用hasOwnProperty仅迭代非继承的属性。



var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";

for (var prop in myArray) {
  if (myArray.hasOwnProperty(prop)) {
    myArray[prop] = 'newValue';
  }
}

console.log(myArray);