Home > Blockchain >  how to get the next item from an javascript array?
how to get the next item from an javascript array?

Time:02-18

So, i have built and array of all the month and i am to get the current month from it by using the getDate function but i wanna scroll through it

const month = ["Januray", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

let d = new Date();
let showMonth = month[d.getMonth()]
monthEl.textContent = showMonth

how to i get the next month when i click on a element with onclick="next()" i have read other various solutions but those consists of complex arrays that i am unable to comprehend due to myself being new programming

CodePudding user response:

You can get the next month by keeping track of the index of the array. Increment the index on a call to next() and pull out the next month from the array using that incremented index month[nextIndex];

The only gotcha is if the index grows beyond the length of the array, which will result in you getting back undefined instead of the month- so we have to check for this. if (nextIndex > month.length - 1) then set the index back to the beginning, 0 and now you have something that will loop through the array.

also you have a small typo in Janurary and Feburary.

const monthEl = document.getElementById("monthEl");
let monthIndex = 0;
const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

let d = new Date();
monthIndex = d.getMonth();
let showMonth = month[monthIndex]
monthEl.textContent = showMonth;

function next() {
  let nextIndex =   monthIndex;
  if (nextIndex > month.length - 1) {
    nextIndex = 0;
    monthIndex = 0;
  }

  let nextMonth = month[nextIndex];
  monthEl.textContent = nextMonth;

}
<div id="monthEl"></div>
<button onClick="next()">next</button>

CodePudding user response:

This function can deal with the scroll I hope it helps you Once it reach the last item of the array will show again the first and so on in a loop.

const month = ["Januray", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

function monthsCal(){
  let refPosition  = -1;
  return {
    next(){
      const pos = (  position)%month.length
      return month[pos]
    }
  }
}

const s = monthsCal()
console.log(s.next()) // Januray
console.log(s.next()) // Feburary
console.log(s.next()) // March
// etc...
  • Related