2013-02-03 10 views
0

如何獲取appointments數組中的對象,其中appointments.id = calEvent.id獲取JavaScript數組中的對象其中appointmentments.id = calEvent.id

appointments.push({ 
    id: id, 
    start: startFormatted, 
    end: endFormatted, 
    title: '<b>' + title + '</b><br><div id="event_body">' + body + '</div>', 
    userId: userid, 
    categoryId: categoryId, 
    counterId: counter 
}); 

eventRender : function(calEvent, $event) { 
    var id = calEvent.id; 

    // get the object in the appointments-array where appointments.id = calEvent.id 
} 
+1

作爲'calEvent'傳遞的對象是什麼? – 0x499602D2

+0

這是jQuery weekcalendar插件中的日曆事件。 calEvent.id等於appointmentments.id中的一個。 – doonot

回答

1

您需要遍歷您appointments陣列的找到匹配id。試試這個:

eventRender : function(calEvent, $event) { 
    var id = calEvent.id;   
    for (var i = 0; i < appointments.length; i++) { 
     if (appointments[i].id == id) { 
      // do something with the appointment... 
      break; 
     } 
    } 
} 
1

你只需通過數組,尋找想要的ID必須循環:

for (var i = 0; i < appointments.length; i++) { 
    if (appointments[i].id == calEvent.id) { 
     // appointments[i] contains the desired id 
     break; 
    } 
} 
0

怎麼樣

appointments[id]={ 

    start: startFormatted, 
    end: endFormatted, 
    title: '<b>' + title + '</b><br><div id="event_body">' + body + '</div>', 
    userId: userid, 
    categoryId: categoryId, 
    counterId: counter 
}; 

然後

eventRender : function(calEvent, $event) { 
    var id = calEvent.id; 
    // get the object in the appointments-array where appointments.id = calEvent.id 
    var obj=appointments[id] 
} 

差指數總是比挑剔循環&推快也慢 編輯添加的,如果你不能改變你建立你的約會的方式,你仍然可以通過它循環一次來創建一個索引數組,以供你的eventrender函數使用,這將更有效率比每循環一次eventrender更有效。您的約會最大,最需要明確索引

+0

約會的索引不等於它的ID。 – doonot

+0

它是如果你把它設置爲 - 無用的評論@doonot;索引一次比每次循環更快 – mikakun

+0

@doonot也看到編輯我的答案;以不同的方式來表達,而不是推動id屬性設置爲id的對象,你添加一個元素到您的數組與索引設置爲id(&那麼甚至不需要一個id屬性);無論如何,如果你更願意永遠循環那就是你的電話,我猜 – mikakun

相關問題