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

Use modulus :

var len = array.length;

var current = array[i];
var previous = array[(i+len-1)%len];
var next = array[(i+1)%len];

Note the +len when getting the previous: the reason we need this is to avoid negative indexes, due to the way modulus works (very unfortunately, -x% is -(x%))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)