簡體   English   中英

Javascript將數組添加到特定索引

[英]Javascript adding array to specific index

當我在應用程序上啟動以下全局變量時:

events = [];

然后,如果我使用以下簡化的代碼片段使用ajax獲取內容:

events[0] = [];

setTimeout(function fetchEventsThisWeek(){

    $.ajax({
      url: '/event/getEventsBetweenDates',
      type: 'POST',
      data : { from_date : currentweek.from_date.toString("yyyy-MM-d") , to_date :  currentweek.to_date.toString("yyyy-MM-d"), limit : limit, offset : offset },
      success: function(data) {
            jQuery.each(data, function(index){
                events[0].push(data[index]['attributes']);
            });




            offset = offset + limit;
            entry_count = entry_count + data.length;

            if(data.length < limit) { // We reached the end of the table so we don't need to call the function again
                renderEvents(current, offset - limit, entry_count);
                //Make sure the current next week button gets enabled because we are done with the results

            } else {
                renderEvents(current,  offset - limit, offset);
                setTimeout(fetchEventsThisWeek, 150); // There are more results, continue
            }

      }
    })
}, 150);

該遞歸函數僅獲取兩個日期之間的所有事件,並不斷調用自身,直到數據庫中沒有記錄為止。 我的問題是:

使用變量:

events[0] = [];

我想將數組的索引指定為我的星期條目。 因此,如果我尋找一個特定的星期,我可以獲取所有已經由數組索引從我的數組中獲取的條目。

我的問題是,當我想獲取更多星期時,例如:

events[1] = [];// Index 1 would represent the next week

該數組只是在擴展大小,所有都附加到末尾,所以我有一個大數組,而不是多維數組。 為什么是這樣? 我如何實現這種行為?

編輯:讓我擴大我的問題。

我在events變量中需要幾個json對象數組。 所以..

events[0] = [ /*contains array of json objects */];
events[1] = [ /*contains array of json objects */];
events[2] = [ /*contains array of json objects */];

每個數組索引代表1周。 因此,索引0是當前星期,索引1是星期1,索引2是星期2,依此類推。 我什至要執行以下操作,但我不知道是否可行:

events[-1] = [ /*contains array of json objects */];

索引-1表示過去1周。 有人能讓我知道這是否可能嗎?

您正在尋找Array.unshift

events.unshift([]);

文獻資料

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM