2013-01-17 11 views
14

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.

+0

"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. –

+0

@ lethal-guitar so che non è la natura di un array, ho detto letteralmente. – Googlebot

risposta

8

come stai parlando di "ciclo illimitato" presumo che il tuo ciclo sia qualcosa del genere

var i = 0, 
    l = array.length; 

while(true) // keep looping 
{ 
    if(i >= l) i = 0; 

    // the loop block 

    if(/* something to cause the loop to end */) break; // <-- this let execution exit the loop immediately 

    i+=1; 
} 

Il modo più efficiente per raggiungere il tuo obiettivo è l'ingenuo uno: controllo

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

ovviamente cache i lunghezza della matrice in una variabile

var l = array.length; 

e (migliore stile) "vars" fuori dal ciclo

var previuos, 
    current, 
    next; 

Si noti che se si accede la matrice sola lettura ci sarebbe un modo più veloce (ma un po 'strano):

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.pop(); 
array[-1] = null; 
32

Uso modulus:

var len = array.length; 

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

Annotare il +len quando ottiene la precedente: il motivo per cui abbiamo bisogno di questo è quello di evitare gli indici negativi, a causa dei lavori modo modulo (molto purtroppo, -x% è -(x%))

1

è necessario ridurre; una funzione dolce costruito per ottenere valori precedenti e successivi della serie

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { 
    return previousValue + currentValue; 
}); 
+3

Per chiarire, 'previousValue' è in realtà un' accumulator', poiché non è il precedente valore dell'array, ma cosa è stato restituito dal richiamo precedente del callback. – evolutionxbox

2

da aggiungere alla @Denys risposta - questo è come si può creare una funzione riutilizzabili

var theArray = [0, 1, 2, 3, 4, 5]; 
var currentIndex = 0; 

function getAtIndex(i) { 
    if (i === 0) { 
     return theArray[currentIndex]; 
    } else if (i < 0) { 
     return theArray[(currentIndex + theArray.length + i) % theArray.length]; 
    } else if (i > 0) { 
     return theArray[(currentIndex + i) % theArray.length]; 
    } 
} 

// usage 
getAtIndex(-2) 

// you can even go crazy and it still works 
getAtIndex(500) 

Demo jsfiddle

Problemi correlati