我有一个数组,我需要在循环内从数组中获取元素。让我解释,
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']
}
我指的是underscore.js并尝试使用一些本机方法,但它有时会中断。
最佳答案
如何创建一个递归函数来确定索引:
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)])
}