如何循环遍历不同索引的数组,同时仍然遍历整个数组? [英] How to loop through arrays starting at different index while still looping through entire array?

查看:121
本文介绍了如何循环遍历不同索引的数组,同时仍然遍历整个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含5个字符串的数组。如何在索引3处启动for循环并绕过并在索引2处结束?让我举一个例子。

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", "gnarly", "rad", "farout", "awesome"];

想从索引3(farout)开始循环到数组末尾(真棒 )然后继续在索引0到索引2循环。基本上在某个点开始一个数组(除了索引0)并且仍然命中数组中的每个元素。

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.

推荐答案

一种方法是使用索引正常循环数组,并使用模数运算符和偏移量来获取指向数组中正确位置的指针:

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

所以你的循环是每个元素的标准循环。您获取当前位置加上偏移量,并从中除以数组大小得到的余数。直到你到达数组的末尾,它将与i + offset相同。当你到达数组的末尾时,余数将为零,然后从那里开始。

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.

这是一个小提琴

这篇关于如何循环遍历不同索引的数组,同时仍然遍历整个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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