Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
How do I cycle through an array when I call a method?
const directions = ["North", "West", "South", "East"];

I want directions.next(); to cycle through them in order. How do I accomplish that in the latest iteration of the ECMAScript? I want every function that calls for directions to get what .next() established to be next.

Does it need to be its own mini-data structure?

Here's what I want to accomplish:

`["Jason Bourne", "Foma Kinaev", "John Michael Kane"]`.next() # // Jason Bourne
`["Jason Bourne", "Foma Kinaev", "John Michael Kane"]`.next() # // Foma Kinaev
`["Jason Bourne", "Foma Kinaev", "John Michael Kane"]`.next() # // John Michael Kane
`["Jason Bourne", "Foma Kinaev", "John Michael Kane"]`.next() # // Jason Bourne
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could use a generator function to yield the values of your array continuously in a while loop (to enabled circular iteration). Then use the generator to give you an iterator that you can then call .next() on to grab the value:

const directions = ["North", "West", "South", "East"];

function* getItr(arr) {
  while(true) yield* arr;
}

const itr = getItr(directions);
console.log(itr.next().value); // North
console.log(itr.next().value); // West
console.log(itr.next().value); // South
console.log(itr.next().value); // East
console.log(itr.next().value); // North

about 4 years ago · Juan Pablo Isaza Report

0

JavaScript arrays don't maintain any iteration state so you'd need to handle some form of internal index pointer yourself

const directions = ["North", "West", "South", "East"];

Array.prototype._current = 0
Array.prototype.next = function() {
  const cur = this[this._current]
  this._current = (this._current + 1) % this.length
  return cur
}

console.log(directions.next())
console.log(directions.next())
console.log(directions.next())
console.log(directions.next())
console.log(directions.next())

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!