← 中文资源

简体中文版本

取模回卷负的循环索引

% 的符号跟随被除数,向后越界会得到负数:((i % n) + n) % n 这个双取模惯用法能把任意步长都拉回合法下标,循环播放列表与环形缓冲都靠它。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

7 % 3 = 1
-7 % 3 = -1
wrap(-1): bridge
wrap(-2): chorus
wrap(9): verse
after 2 -> bridge
after 3 -> chorus
after -2 -> intro

实现说明

底层就是函数 wrap。 for (const delta of [2, 3, -2]) 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 直接运行文件,输出会带上标签,比如 7 % 3 =、-7 % 3 =、wrap(-1):——输出的每一行都能指回产生它的那次调用。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 wrap。

入口签名:const wrap = (index, length)

核心语句

const wrap = (index, length) => ((index % length) + length) % length;

代码示例

// % takes the sign of the dividend, not the divisor
console.log('7 % 3 =', 7 % 3);
console.log('-7 % 3 =', -7 % 3);

// Double modulo maps any integer — negative or past the end — into range
const wrap = (index, length) => ((index % length) + length) % length;
const playlist = ['intro', 'verse', 'chorus', 'bridge'];
console.log('wrap(-1):', playlist[wrap(-1, playlist.length)]);
console.log('wrap(-2):', playlist[wrap(-2, playlist.length)]);
console.log('wrap(9):', playlist[wrap(9, playlist.length)]);

// Stepping by any delta keeps the cursor inside the playlist
let cursor = 1;
for (const delta of [2, 3, -2]) {
  cursor = wrap(cursor + delta, playlist.length);
  console.log('after', delta, '->', playlist[cursor]);
}