33

在 Javacript 的简单数组循环中

for (var i=0; i<array.length; i++) {

var previous=array[i-1];
var current=array[i];
var next=array[i+1];

}

我需要在无限循环中获取previousand元素。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

什么是最有效的方法来做到这一点。我能想到的唯一方法是在每一轮中检查元素是数组中的第一个还是最后一个。

事实上,我希望以某种方式使数组成为一个封闭的循环,而不是线性的。

4

5 回答 5

83

使用模数

var len = array.length;

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

注意+len获取上一个时:我们需要这个的原因是为了避免负索引,因为模数的工作方式(非常不幸的-x%-(x%)

于 2013-01-17T21:18:41.957 回答
16

当您在谈论“无限循环”时,我假设您的循环是这样的

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;
}

实现目标最有效的方法是天真的方法检查

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

显然将数组的长度缓存在一个变量中

var l = array.length;

和(更好的风格)循环中的“vars”

var previuos,
    current,
    next;

请注意,如果您正在访问只读数组,则会有一种更快(但有些奇怪)的方式:

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;
于 2013-01-17T21:22:58.013 回答
7

添加到@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)

演示 jsfiddle

于 2017-05-30T15:40:24.207 回答
4

你需要减少;一个内置的甜蜜函数来获取数组的上一个和下一个值

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

有关减少的更多信息

于 2016-05-31T07:41:45.687 回答
2

为了简单。

对于数组中的下一个元素:

 currentIndex= (currentIndex+1)%array.length;

对于数组中的前一个元素:

currentIndex= (currentIndex+array.length-1)%array.length;
于 2021-06-05T20:09:31.007 回答