我有一个JavaScript关联数组,比如说:
var myArray = new Object();
myArray["id1"] = "completed";
myArray["id2"] = "notCompleted";
myArray["id3"] = "started";
如何更新此数组中每个项的值,以便输出
myArray["id1"] = "newValue";
myArray["id2"] = "newValue";
myArray["id3"] = "newValue";
答案 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);