javascript - 在递增/递减时将整数限制为数组 indeces

标签 javascript math

考虑以下代码(keyCode 用于向后兼容):

/**
 * Navigate through the items.
 *
 * @param {Event} event
 * @return void
 */
navigate(event) {

    if (event.keyCode === 38 || event.key === "ArrowUp") {
        this.active = this.active + 1 > this.items.length ? 0 : this.active + 1;
    }

    if (event.keyCode === 40 || event.key === "ArrowDown") {
        this.active = this.active - 1 < 0 ? this.items.length : this.active - 1;
    }

}

如果上面的内容不清楚,我正在尝试执行以下操作:

  • 递增this.active时,确保其不大于this.items的长度,如果大于,则返回0
  • 递减this.active时,确保其不小于0,如果小于,则返回到this.items的长度

上面的代码工作得很好,但我知道它可以做得更好、更有效。例如,调用 this.active -1 两次效率低下。

有没有办法使用Math.minMath.Max之类的东西来优雅地实现这一点?

最佳答案

我会使用模运算符:

navigate(event) {
    const { length } = items;
    if (event.keyCode === 38 || event.key === "ArrowUp") {
        this.active = (this.active + 1) % length;
    } else if (event.keyCode === 40 || event.key === "ArrowDown") {
        this.active = (this.active - 1 + length) % length;
    }
}

关于javascript - 在递增/递减时将整数限制为数组 indeces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57129774/

相关文章:

javascript - 导入的函数未定义

javascript - 文本框中的不同字体

javascript - 访问后不要更改表格行的颜色

algorithm - 什么是特征值和展开式?

php - MySQL - 获取列中的平均值

javascript - 为什么backbone全程使用_.extend()方法?

javascript - 如何在jquery中动态打印id

math - 量化专业随机生成器的非随机性?

c++ - 从俯仰角检测头部点头姿势

algorithm - 使用主定理的推广求解方程