【发布时间】:2019-03-13 06:03:47
【问题描述】:
我有一个包含 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);
}
}
如果我需要向前或向后移动,我正在尝试在上面的代码中找到。在上面的示例中,我希望答案为 -6,但我得到答案 10。我在循环中有点困惑。有没有更好更智能的方法来做到这一点?
【问题讨论】:
标签: javascript logic