简体   繁体   中英

Javascript adding array to specific index

When i have the following global variable on my application start :

events = [];

Then if i go fetch something with ajax with the following simplified code snippet :

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);

This recursive function just fetches all events between two dates and keeps calling itself until there is no record in the db left. My problem is:

With the variable:

events[0] = [];

I want to specify the index of the array as my week entry. So if i look for a specific week, i can get all the entries that already have been fetched from my array by the array index.

My problem is, when i want to fetch more weeks, so for example:

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

The array just expands in size and all gets appended to the end, so i have one big array and not a multidimensional one. Why is this? And how can i achieve this behaviour?

Edit: Let me expand on my question.

I need several arrays of json objects in the events variable. So..

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

Each array index represent 1 week. So index 0 is the current week, index 1 is week 1, index 2 is week 2 and so forth. I even want to do the following but i don't know if this is even possible:

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

Where the index -1 would be 1 week in the past. Could anybody let me know if this is possible?

You're looking for Array.unshift :

events.unshift([]);

Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM