Javascript - 动态从数组中获取元素
Posted
技术标签:
【中文标题】Javascript - 动态从数组中获取元素【英文标题】:Javascript - fetch elements from array dynamically 【发布时间】:2017-02-22 23:11:57 【问题描述】:我有一个数组,我需要从循环内的数组中获取元素。让我解释一下,
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 并尝试使用一些本机方法,但它在某些时候会中断。
【问题讨论】:
所以你想旋转阵列?见***.com/questions/1985260/javascript-array-rotate 嗯loopLimit
是一个数字,那为什么是 loopLimit.length
?不应该只是loopLimit
吗?
@Unicode 你是对的,已编辑
【参考方案1】:
如何创建一个递归函数来确定索引:-
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)])
【讨论】:
以上是关于Javascript - 动态从数组中获取元素的主要内容,如果未能解决你的问题,请参考以下文章
如何创建多个从同一个数组中获取值的动态下拉列表,而无需更改 Javascript 中的其他下拉列表
怎么用javascript/jquery在当前页面获取动态添加的表单的name和值并且变成整个数组