偏移量编号的数组项索引 [英] array item index from an offset number

查看:104
本文介绍了偏移量编号的数组项索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

var list = ['first', 'second', 'third'];

现在我显然可以通过它们的索引分别访问第一个,第二个和第三个元素0 1和2如果我尝试访问 list [4] ,我会收到错误消息。

Now I can obviously access the first, second and third element by their indexes, respectively 0 1 and 2. If I try to access list[4] I will get an error.

有没有办法,如果我尝试访问数组外部的第n个元素,则计数从头开始?这样 list [4] 会返回第一个?

Is there a way so that, if I try to access the nth element outside of the array, the count starts form the beginning? so that list[4] would return "first"?

请记住该数字也可以更大

Keeping in mind that the number could also be bigger multiple times the length of the array itself.

推荐答案


  1. 访问不存在的数组元素不会抛出任何错误,但是返回 undefined

var list = ['first', 'second', 'third'];
console.log(list[3]);
// undefined
console.log(list[4]);
// undefined


  • 当索引较大时环绕数组比长度大,那么您可以使用mod运算符,例如

  • To wrap around the array, when the index is greater than the length, then you can use the mod operator, like this

    console.log(list[3 % list.length]);
    // first
    console.log(list[4 % list.length]);
    // second
    


  • 这篇关于偏移量编号的数组项索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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