All All - 1 year ago 46
Javascript Question

How to get the previous and next elements of an array loop in JavaScript?

In a simple array loop of Javacript as

for (var i=0; i<array.length; i++) {

var previous=array[i-1];
var current=array[i];
var next=array[i+1];


I need to get the
elements in an unlimited cycle. For example,

The previous element of the first element in the array is the array last element
The next element of the last element in the array is the array first element

What can be the most efficient way to do this. The only way I can think of is to check if the element is the first or last in the array in every round.

In fact, I hope to make the array a closed cycle somehow, rather than linear.

Answer Source

as you're talking about "unlimited cycle" I assume your loop is something like that

var goOn = true,
    i = 0,
    l = array.length;

    if(i >= l) i = 0;

    // you loop block

    if(/* something to cause the loop to end */) goOn = false;


the most efficient way is the only one you can think of (checking)

    var previous=array[i==0?array.length-1:i-1];
    var current=array[i];
    var next=array[i==array.length-1?0:i+1];

obviously cache the length of the array in a variable

var l = array.length;

and (better style) the "vars" out of the cycle

var previuos,

Note that if you are accessing the array read only there would be a faster (but somewhat strange) way:

l = array.length;
array[-1] = array[l-1]; // this is legal
array[l] = array[0];

for(i = 0; i < l; i++)
    previous = array[i-1];
    current = array[i];
    next = array[i+1];

// restore the array

array[-1] = null;