How to loop through arrays starting at different index while still looping through entire array?

后端 未结 3 1183
野的像风
野的像风 2021-02-04 10:16

Suppose I had an array of 5 strings. How can I start a for loop at index 3 and go around and end up at index 2? Let me give an example.

var myArry = [\"cool\",         


        
相关标签:
3条回答
  • 2021-02-04 10:36

    One way is to loop through the array using an index as normal, and use the modulus operator with your offset, to get a pointer to the correct place in the array:

    var myArry = ["cool", "gnarly", "rad", "farout", "awesome"];
    var offset = 3;
    for( var i=0; i < myArry.length; i++) {
        var pointer = (i + offset) % myArry.length;
        console.log(myArry[pointer]);
    }
    

    So your loop is a standard loop through every element. You take the current position, plus offset, and get the remainder from that divided by the size of the array. Until you reach the end of the array that will just be the same as i + offset. When you reach the end of the array, the remainder will be zero, and go from there.

    Here's a fiddle.

    0 讨论(0)
  • 2021-02-04 10:36
    var startAt = 3;
    for(var index = 0;index<myArry.length;index++){
      console.log(myArry[startAt]);
      if(startAt==myArry.length-1){
            startAt = -1;
      } 
      startAt++;
    }
    
    0 讨论(0)
  • 2021-02-04 10:43

    Here's what you need:

    var start = 3;
    for(var z=0;z<myArry.length;++z) {
      var idx = (z+start) % myArry.length;
      console.log(myArry[idx]);
    }
    
    0 讨论(0)
提交回复
热议问题