我知道模数会返回除法的余数,但我不明白当您需要重置数组索引时它是如何工作的。
假设我们有这段代码:
let numbers = [1, 2, 3]
let index = 0
for 1...6 {
let item = numbers[index % numbers.count]
print(item)
index += 1
}
我理解index之前的操作等于numbers.count,会返回index。我还了解到,当索引达到 3,即数组中的项目数时,它将返回 0(这将显示数组的第一项)。但是,我不明白它是如何继续按顺序显示数组的。
如果index为4,那么运算就是4除以3,余数为1。那么,显示的数字应该是1,2,3,1,1吧?我的意思是,索引永远不会被分配回 0,所以它只会继续递增。
到达数组末尾后,重置索引的模数方法如何工作?
为什么模数方法比下面重置索引的方法更好?
if index >= numbers.count {
index = 0
}
最佳答案
您的描述有一点偏差。 index
从 0 开始迭代,而不是 1(不要将行 for 1...6
与 index
的值混淆。
计算一下。您将 index
从 0 迭代到 5。numbers.count
为 3。
对于每个索引,结果是index % numbers.count
。
index: 0 1 2 3 4 5
result: 0 1 2 0 1 2
item: 1 2 3 1 2 3
关于arrays - 使用模数运算符重置索引如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47017928/