2016-10-13 5 views
1

Ich habe ein Array und ich muss Elemente aus dem Array innerhalb einer Schleife holen. Lassen Sie mich erklären,Javascript - Elemente aus Array dynamisch abrufen

var globalArray = ['apple','orange','melon','banana'], 
    loopLimit = 5, 
    fruitsPerLoop = 3; 

for (var i=1; i<=loopLimit; i++) { 
    // when the loop runs for the first time i need to grab the first 3 elements from the array since fruitsPerLoop is 3 and for the second time the next 3 (out of bound should be taken care) and for third time etc... 
    //Pseudo with fruitsPerLoop as 3 
    when i = 1 ==> globalArray should be ['apple','orange','melon'] 
     i = 2 ==> globalArray should be ['banana', 'apple','orange'] 
     i = 3 ==> globalArray should be ['melon','banana', 'apple'] 
     i = 4 ==> globalArray should be ['orange','melon','banana'] 
     i = 5 ==> globalArray should be ['apple','orange','melon'] 
} 

Ich bezog Underscore.js und versuchen auch einige native Methoden zu verwenden, aber es bricht irgendwann.

+0

So wollen Sie das Array drehen? Siehe http://stackoverflow.com/questions/1985260/javascript-array-rotate – Barmar

+0

Um 'loopLimit' ist eine Zahl, warum also' loopLimit.length'? Sollte es nicht einfach "loopLimit" sein? –

+0

@Unicode Sie sind richtig, bearbeitet – Sai

Antwort

0

Wie wäre es eine rekursive Funktion Erzeugen des Index zu bestimmen: -

var globalArray = ['apple', 'orange', 'melon', 'banana'], 
 
    loopLimit = 5, 
 
    fruitsPerLoop = 3; 
 

 
function getIndex(i, minus) { 
 
    var index = i - minus; 
 
    if (index < 0) 
 
    return getIndex(globalArray.length, minus - i) 
 
    return globalArray[index]; 
 
} 
 

 
for (var i = 1; i <= loopLimit; i++) { 
 
    console.log([getIndex(1, i), getIndex(2, i), getIndex(3, i)]) 
 
}

Verwandte Themen