正在更新数组对象值

Updating array object values

本文关键字:对象 数组 更新      更新时间:2023-09-26

我想更新全局数组中保存在工厂中的一些值。我使用get方法来获取数据,但set函数不知何故没有完成它的工作,数组中的值也没有得到更新。我错过了什么?

.factory('messageList', function () {
   var Messages = 
    [
        {   "title":"Cash in", "icon":"ion-social-euro", 
            "dailyValue": "0", "weeklyValue": "0", "monthlyValue": "0", 
            "category": "financial", "active": "true"
        },
        {   "title":"Sales orders", "icon":"ion-social-euro", 
            "dailyValue": "0", "weeklyValue": "0", "monthlyValue": "0", 
            "category": "sales", "active": "true"
        }
    ]
return {
   get: function() {
      return Messages;
   },
   set: function(title, key, newValue) {
       for (var i = 0; i < Messages.length; i++) {
          if(Messages[i].title == title){
            Messages[i].key = newValue;
          }
       }
   }
 }
})

这就是我尝试更新控制器中的值的方式:

messageList.set("Sales orders","dailyValue", $Scope.sum);

由于key是一个变量,请使用此

Messages[i][key] = newValue;

Messages[i].key将在对象中查找具有关键字"key"的元素,而不是具有变量值的关键字