[SOLVED] how to get the next item from an javascript array?

Issue

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

Solution

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>

Answered By – Andrew Lohr

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.