DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

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

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];
  }
}

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)