Goo*_*bot 25 javascript arrays loops
在一个简单的Javacript数组循环中
for (var i=0; i<array.length; i++) {
var previous=array[i-1];
var current=array[i];
var next=array[i+1];
}
Run Code Online (Sandbox Code Playgroud)
我需要在无限循环中获得previous和next元素.例如,
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
Run Code Online (Sandbox Code Playgroud)
什么是最有效的方法.我能想到的唯一方法是检查元素是每一轮中数组的第一个还是最后一个.
实际上,我希望以某种方式使数组成为闭合循环,而不是线性.
Den*_*ret 59
使用模数:
var len = array.length;
var current = array[i];
var previous = array[(i+len-1)%len];
var next = array[(i+1)%len];
Run Code Online (Sandbox Code Playgroud)
注意到+len获得前一个时间:我们需要这个的原因是为了避免负指数,因为模数的工作方式(非常不幸的-x%是-(x%))
Pao*_*olo 11
当你在谈论"无限循环"时,我认为你的循环是这样的
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;
}
Run Code Online (Sandbox Code Playgroud)
实现目标的最有效方法是天真的:检查
var previous=array[i==0?array.length-1:i-1];
var current=array[i];
var next=array[i==array.length-1?0:i+1];
Run Code Online (Sandbox Code Playgroud)
显然在变量中缓存数组的长度
var l = array.length;
Run Code Online (Sandbox Code Playgroud)
和(更好的风格)"vars"走出循环
var previuos,
current,
next;
Run Code Online (Sandbox Code Playgroud)
请注意,如果您正在访问阵列只读会有一个更快(但有些奇怪的)方式:
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;
Run Code Online (Sandbox Code Playgroud)
添加到@Denys 答案 - 这就是您可以创建可重用功能的方法
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)
Run Code Online (Sandbox Code Playgroud)
为了简单起见。
对于数组中的下一个元素:
currentIndex= (currentIndex+1)%array.length;
Run Code Online (Sandbox Code Playgroud)
对于数组中的前一个元素:
currentIndex= (currentIndex+array.length-1)%array.length;
Run Code Online (Sandbox Code Playgroud)