Categories
JavaScript Answers

How to move to prev/next element of an array with JavaScript?

Spread the love

To move to prev/next element of an array with JavaScript, we can define our own array class.

For instance, we write

class TraversableArray extends Array {
  next() {
    return this[++this.current];
  }
}

to define the TraversableArray class that extends the Array class.

In it, we add the next method that returns the object at the current index after incrementing it by 1.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *