将“undefined”索引映射到Array

时间:2014-01-30 15:04:43

标签: javascript arrays

假设我们有一个像这样的数组:

var example = ["a", "b", "c", "d", "e"]

我们知道我们可以访问0-4的索引:

example[0] == "a"
example[1] == "b"
example[2] == "c"
example[3] == "d"
example[4] == "e"

但是,我们还希望映射undefined索引。例如:

example[0] == example[5] == example[10] == example[15] == example[20] == "a"
example[1] == example[6] == example[11] == example[16] == example[21] == "b"
example[2] == example[7] == example[12] == example[17] == example[22] == "c"
example[3] == example[8] == example[13] == example[18] == example[23] == "d"
example[4] == example[9] == example[14] == example[19] == example[24] == "e"

虽然这可能很简单,但数学运算只是逃避了我的想法。请注意,example.length并未修复,有时可能会有所不同。怎么会这样呢?

1 个答案:

答案 0 :(得分:7)

您似乎想要使用modulo

example[i%example.length]