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 previous and next 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.
as you’re talking about “unlimited cycle” I assume your loop is something like that
The most efficient way to achieve your goal is the naive one: checking
obviously cache the length of the array in a variable
and (better style) the “vars” out of the cycle
Note that if you are accessing the array read only there would be a faster (but somewhat strange) way: