Javascript 递增/递减时,将整数限制为数组索引
考虑以下代码(Javascript 递增/递减时,将整数限制为数组索引,javascript,math,Javascript,Math,考虑以下代码(keyCode用于向后兼容): /** *浏览项目。 * *@param{Event}Event *@返回无效 */ 导航(事件){ 如果(event.keyCode==38 | | event.key===“ArrowUp”){ this.active=this.active+1>this.items.length?0:this.active+1; } 如果(event.keyCode==40 | | event.key===“ArrowDown”){ this.active=t
keyCode
用于向后兼容):
/**
*浏览项目。
*
*@param{Event}Event
*@返回无效
*/
导航(事件){
如果(event.keyCode==38 | | event.key===“ArrowUp”){
this.active=this.active+1>this.items.length?0:this.active+1;
}
如果(event.keyCode==40 | | event.key===“ArrowDown”){
this.active=this.active-1<0?this.items.length:this.active-1;
}
}
如果以上内容不清楚,我将尝试以下操作:
- 当递增
时,确保它不大于this.active
的长度,如果是,则将其返回到this.items
0
- 当递减
时,确保其不小于0,如果小于0,则将其返回到此.active
此.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;
}
}
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;
}
}