繁体   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