Javascript循环数组查找下一个元素

Javascript循环数组查找下一个元素,javascript,logic,Javascript,Logic,我有一个n个元素的数组。我在一个给定的位置,比如说x,我需要移动到位置y,我需要找出前进和后退遍历数组时的差异或步数 const foo = Array.from(Array(15).keys()); const length = foo.length; const currentItem = 2; const next = 12; let diff = currentItem - next; if (diff < 0) { if (next > currentItem) {

我有一个n个元素的数组。我在一个给定的位置,比如说x,我需要移动到位置y,我需要找出前进和后退遍历数组时的差异或步数

const foo = Array.from(Array(15).keys());
const length = foo.length;
const currentItem = 2;
const next = 12;
let diff = currentItem - next;
if (diff < 0) {
  if (next > currentItem) {
    diff = next - currentItem;
    console.log((diff));
  } else {
    diff = length - Math.abs(diff);
    console.log(-diff);
  }
} else {
  if (next < currentItem) {
    console.log(-(diff));
  } else {
    console.log(diff);
  }
}
const foo=Array.from(Array(15.keys());
常量长度=foo.length;
const currentItem=2;
常数next=12;
让diff=currentItem-next;
如果(差异<0){
如果(下一步>当前项){
差异=下一个-当前项目;
console.log((diff));
}否则{
diff=长度-数学绝对值(diff);
console.log(-diff);
}
}否则{
如果(下一个
如果我需要向前或向后移动,我会尝试使用上面的代码。在上面的例子中,我希望答案是-6,但我得到的答案是10。我在循环中有点困惑。有更好更聪明的方法吗?

以下是我的方法:

//JavaScript中的%运算符是余数运算符。
//以下函数定义了模运算符。
常数模=(x,y)=>(x%y+y)%y;
//定律:mod(开始+最短路径(开始、结束、长度)、长度)==end
常量最短路径=(开始、结束、长度)=>{
const forward=mod(结束-开始,长度);
const backward=mod(开始-结束,长度);
返回向前>向后?-向后:向前;
};
const shortestPathLaw=(开始、结束、长度)=>
mod(开始+最短路径(开始、结束、长度),长度)==结束;
断言(最短路径法(4,6,10));
断言(最短路径法(8,6,10));
console.log(最短路径(4,6,10));//2.
console.log(最短路径(8,6,10));//-2