简体   繁体   中英

Javascript Array splice method show 50 items at a time with forward backword button

Hi all I have an array that I would like to scroll through with buttons previous and next. How can I use the array splice method to do this and keep track of the array index? I am always displaying in groups of 50

//Previous page button calls this function
var previousPage = function(){
   pageCount = pageCount -50;
   arraySlice = peopleArray.slice(pageCount -50, pageCount);
   for(i = 0; i<arraySlice.length;i++){
       var key = arraySlice[i];
       createCircles(key.gplusUrl, key.gplusImg, divId, key.displayName, divId);
   }
};


//Next page button calls next page function
var nextPage = function(){

   //I am using pageCount for the index pageCount
   //I increment the pageCount by 50


      pageCount = pageCount +50; 
       //Splice the 
       arraySlice = peopleArray.slice(pageCount, pageCount +50);

      //Loop through the array I sliced
      for(i = 0; i<arraySlice.length;i++){
          key = arraySlice[i];
          //This function displays the items from the array you can ignore this
          createCircles(key.gplusUrl, key.gplusImg, divId, key.displayName, divId);
      }
   };

Lets say your current pageCount is at 200 in your giant array:

<-----100-----150----- 200 -----250-----300----->

What happens when you call nextPage() ? You increment pageCount to 250, and then slice from (pageCount, pageCount+50) which is (250-300). So now you end up displaying this portion of your array:

<-----100-----150-----200----- 250-----300 ----->

Next, lets say you called previousPage() . You decrement pageCount to 200 and then slice from (pageCount-50, pageCount) which is (150-200). So you end up displaying this portion:

<-----100----- 150-----200 -----250-----300----->

Calling nextPage() will display (250-300) again. Notice how its impossible to display (200-250)?

The reason is because in your previousPage implementation, you decremented pageCount by 50, and then choose to select the 50 items before it. Essentually, you've moved your selection down by 100 when you only meant to go back by 50. Change your previousPage implementation to also slice from (pageCount, pageCount+50).

Also, make sure you check after you decrement pageCount that it's not negative because that will end up selecting from the end of the array.

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