我有一個功能,我在移動設備上安排提醒。我正在構建一個重複項目數組並增加提交給該數組的每個對象的兩個屬性,對象中的所有其他內容保持不變。當我開始循環的第一次迭代時,它會按預期將對象推入數組,但在調試過程中,在我進入對象或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 {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)}] –
爲什麼你不能只用'id:i + 1'?我想我對某些功能並不確定。 – manonthemat
,因爲它查看可能預先存在於此函數調用中的對象數組,並需要在數組中找到「最大」id編號,然後從那裏開始遞增。這會簡化它,但我沒有這個選擇。 –