简体   繁体   English

如何循环遍历不同索引的数组,同时仍然遍历整个数组?

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

Suppose I had an array of 5 strings. 假设我有一个包含5个字符串的数组。 How can I start a for loop at index 3 and go around and end up at index 2? 如何在索引3处启动for循环并绕过并在索引2处结束? Let me give an example. 让我举个例子。

var myArry = ["cool", "gnarly", "rad", "farout", "awesome"];

Would like to start at index 3 ("farout") loop through to end of array ("awesome") then continue looping at index 0 through index 2. Basically beginning an array at some point (other than index 0) and still hit every element in the array. 想从索引3(“farout”)循环开始到数组结尾(“awesome”)然后继续在索引0到索引2循环。基本上在某个点(索引0除外)开始一个数组并仍然每个数组中的元素。

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. 直到你到达数组的末尾,它将与i + offset相同。 When you reach the end of the array, the remainder will be zero, and go from there. 当你到达数组的末尾时,余数将为零,然后从那里开始。

Here's a fiddle . 这是一个小提琴

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]);
}
var startAt = 3;
for(var index = 0;index<myArry.length;index++){
  console.log(myArry[startAt]);
  if(startAt==myArry.length-1){
        startAt = -1;
  } 
  startAt++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM