如何获得previous并在JavaScript中数组循环的下一个元素? [英] How to get the previous and next elements of an array loop in JavaScript?

查看:119
本文介绍了如何获得previous并在JavaScript中数组循环的下一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javacript的简单数组环路

In a simple array loop of Javacript as

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

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

}

我需要在一个无限循环中的 previous 接下来元素。例如,

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

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

What can be the most efficient way to do this. The only way I can think of is to check if the element is the first or last in the array in every round.

其实,我希望制作阵列的封闭循环不知何故,而不是线性的。

In fact, I hope to make the array a closed cycle somehow, rather than linear.

推荐答案

当你在谈论无限循环我假设你的循环是类似的东西。

as you're talking about "unlimited cycle" I assume your loop is something like that

var goOn = true,
    i = 0,
    l = array.length;

while(goOn)
{
    if(i >= l) i = 0;

    // you loop block

    if(/* something to cause the loop to end */) goOn = false;

    i+=1;
}

最有效的方式是你能想到的只有一个(检查)

the most efficient way is the only one you can think of (checking)

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

明显缓存阵列的长度中的可变

obviously cache the length of the array in a variable

var l = array.length;

和(更好的风格)的瓦尔跳出循环

and (better style) the "vars" out of the cycle

var previuos,
    current,
    next;

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

Note that if you are accessing the array read only there would be a faster (but somewhat strange) way:

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;

这篇关于如何获得previous并在JavaScript中数组循环的下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆