我查看了https://math.stackexchange.com/questions/519845/modulo-of-a-negative-number和Modulo operation with negative numbers,但我仍然想知道如何使用负模值来获取范围内的项目。
下面是一个简化的用例,下面有一个幻灯片,其中包含3张幻灯片(slidesCount = 3
):
slide indexes: 0 1 2
现在,我想从这些数字中访问正确的幻灯片:
-2 -1 0 1 2 3 4
should match slide:
1 2 0 1 2 0 1
因此,我使用index % slidesCount
讨论了以下情况:
0 1 2 3 4
但不是负值。 -1 % 3
返回-1
,因此如果index为负,slidesCount + index % slidesCount
是正确的表达式吗?
首先,有没有一种更简单/更智能的书写方式:
index = index % slidesCount + (index < 0 ? slidesCount : 0)
现在我的问题是每张幻灯片显示3个可见项目的幻灯片, 在最后一张幻灯片中可能只有一项(索引为9),因此从这些数字中可以得出:
-3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12
我要匹配幻灯片:
9 0 3 6 9 0
我希望下图有意义!请帮助我以最少if
s的时间得出正确的方程式:
-3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12
|________| |______________________________________________|
|| || ||
|| Math.floor( i / visibleSlides )
Math.ceil(i / visibleSlides) || ||
|| || ||
\/ \/ \/
-1 0 1 2 3 4
|___| |_______________________| |___|
|| || ||
slidesCnt + i % visibleSlides i % visibleSlides || ??
|| || ||
\/ \/ \/
3 0 1 2 3 0
|| i * visibleSlides
\/
9 0 3 6 9 0
答案 0 :(得分:0)
最后,这就是我解决问题的方式:
// Prevents out of range.
// e.g. -1, -2, 12, 13
let newIndex = (index + slidesCount) % slidesCount
// Calculates how many items are missing on last slide.
// e.g. if 10 slides with 3 visible slides, 2 missing slides on last slide.
let lastSlideItems = slidesCount % visibleSlides || visibleSlides
let missingItems = visibleSlides - lastSlideItems
// If index is negative adjust by adding the missing slides.
newIndex += index < 0 ? missingItems : 0
// Always get the first item of the series of visible items.
// e.g. if index is 8 and 3 visible slides, newIndex will be 6.
newIndex = Math.floor(newIndex / visibleSlides) * visibleSlides