Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 递增/递减时,将整数限制为数组索引_Javascript_Math - Fatal编程技术网

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
  • 当递减
    此.active
    时,确保其不小于0,如果小于0,则将其返回到
    此.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;
    }
}