2016-12-13 82 views
0

我有一個功能,我在移動設備上安排提醒。我正在構建一個重複項目數組並增加提交給該數組的每個對象的兩個屬性,對象中的所有其他內容保持不變。當我開始循環的第一次迭代時,它會按預期將對象推入數組,但在調試過程中,在我進入對象或push函數之前,第二次迭代會更新數組中的'reminderId'值。 'time_to_notify'按預期遞增,只有'reminderId'被替換。第一個陣列項目被覆蓋第二個推入陣列,並增加重複屬性

在接下來的迭代它遞增和我結束了一個數組,看起來像這樣:

[ 
0{id: 2, title: "Athens", text: "Test", at: Tue Dec 13 2016 16:00:28 GMT-0600 (CST)} 
1{id: 3, title: "Athens", text: "Test", at: Wed Dec 14 2016 16:00:28 GMT-0600 (CST)} 
2{id: 3, title: "Athens", text: "Test", at: Thu Dec 15 2016 16:00:28 GMT-0600 (CST)} 
] 

應該是這樣的:

[ 
0{id: 1, title: "Athens", text: "Test", at: Tue Dec 13 2016 16:00:28 GMT-0600 (CST)} 
1{id: 2, title: "Athens", text: "Test", at: Wed Dec 14 2016 16:00:28 GMT-0600 (CST)} 
2{id: 3, title: "Athens", text: "Test", at: Thu Dec 15 2016 16:00:28 GMT-0600 (CST)} 
] 

注意日期正確遞增,但有是「提醒ID」如何增加的問題,而我一直在嘲笑我的頭幾個小時。

我的代碼建立這個如下。這可能是一個超級簡單的東西,非常感謝任何幫助。

if(isIOS){ 
     var notificationItem = []; 
     var reminderId = -1; 
     for(i=0; i < 3; i++){ 

      var iOSNotification = {}; 
      if ($scope.scheduledContainer.length == 0 && notificationItem.length == 0) { 
      reminderId = 1; 
      } else if ($scope.scheduledContainer.length > 0) { 
      var convertDate = new Date(time_to_notify); 
      convertDate.setDate(convertDate.getDate()+1); 
      time_to_notify = convertDate; 

      var max = $scope.scheduledContainer.reduce(function(prev, current) { 
      return (prev.y > current.y) ? prev : current 
      }); //$scope.scheduledContainer contains array items if they alreay exist 
      reminderId = ++max.id; 
     } else if (notificationItem.length > 0) { 
      var convertDate = new Date(time_to_notify); 
      convertDate.setDate(convertDate.getDate()+1); 
      time_to_notify = convertDate; 

      var max = notificationItem.reduce(function(prev, current) { 
      return (prev.y > current.y) ? prev : current 
      }); //notificationItem is a temp array that contains first time notification repeats 
      reminderId = ++max.id; 
     } 


     iOSNotification = { 
      id: reminderId, 
      title: mxAppConfig.RegionId, 
      text: task.msg, 
      at: time_to_notify 
     } 


     notificationItem.push(iOSNotification); 

     } 


    } 

回答

0

更改預增

reminderId = ++max.id; 

後增量

reminderId = max.id++; 
+0

感謝您的想法,但沒有去。這是現在的數組:[0 {id:2,title:「Athens」,text:「Test」,at:Tue Dec 13 2016 16:15:52 GMT-0600(CST)} 1 {id:2,title :「雅典」,文本:「測試」,時間:Wed Dec 14 2016 16:15:52 GMT-0600(CST)} 2 {id:1,title:「Athens」,text:「Test」 Thu Dec 15 2016 16:15:52 GMT-0600(CST)}] –

+0

爲什麼你不能只用'id:i + 1'?我想我對某些功能並不確定。 – manonthemat

+0

,因爲它查看可能預先存在於此函數調用中的對象數組,並需要在數組中找到「最大」id編號,然後從那裏開始遞增。這會簡化它,但我沒有這個選擇。 –

0

我發現這個問題。在我將它推入數組之前,我正在添加對該對象的引用。這是持有一個實例的對象,它會自動更新數組中的'id'屬性。當我收集if/else語句中的值時,刪除它並構建對象,從而構建一個新的對象,以便每次都進行推送。