Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda