How to get the previous and next elements of an array loop in JavaScript?

前端 未结 4 1260
攒了一身酷
攒了一身酷 2020-12-23 12:09

In a simple array loop of Javacript as

for (var i=0; i         


        
4条回答
  •  执笔经年
    2020-12-23 12:40

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

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

    The most efficient way to achieve your goal is the naive one: 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;
    

提交回复
热议问题