考虑以下代码(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.min
和Math.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/