In un semplice ciclo array di Javacript comeCome ottenere gli elementi precedente e successivo di un loop di array in JavaScript?
for (var i=0; i<array.length; i++) {
var previous=array[i-1];
var current=array[i];
var next=array[i+1];
}
devo ottenere le previous
e next
elementi di un ciclo illimitata. Ad esempio,
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
Quale può essere il modo più efficiente per farlo. L'unico modo che posso pensare è di verificare se l'elemento è il primo o l'ultimo della matrice in ogni round.
In effetti, spero di rendere l'array un ciclo chiuso in qualche modo, piuttosto che lineare.
"rendere la matrice un ciclo chiuso "- non è possibile. Potresti forse implementare una sorta di struttura ring-buffer usando gli oggetti, ma gli array sono sempre lineari. –
@ lethal-guitar so che non è la natura di un array, ho detto letteralmente. – Googlebot