【问题标题】:Javascript circular array find next elementJavascript循环数组查找下一个元素
【发布时间】: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


    【解决方案1】:

    我会这样做:

    // The % operator in JavaScript is the remainder operator.
    // The following function defines the modulo operator.
    const mod = (x, y) => (x % y + y) % y;
    
    // Law: mod(start + shortestPath(start, end, length), length) === end
    const shortestPath = (start, end, length) => {
        const forward  = mod(end - start, length);
        const backward = mod(start - end, length);
        return forward > backward ? -backward : forward;
    };
    
    const shortestPathLaw = (start, end, length) =>
        mod(start + shortestPath(start, end, length), length) === end;
    
    console.assert(shortestPathLaw(4, 6, 10));
    console.assert(shortestPathLaw(8, 6, 10));
    
    console.log(shortestPath(4, 6, 10)); // 2
    console.log(shortestPath(8, 6, 10)); // -2

    我们使用modulo operator 来计算从A 点到B 点的前向距离(即B - A)。从 A 点到 B 点的向后距离与从 B 点到 A 点的向前距离相同(即A - B)。然后我们选择两个距离中较短的一个,如果我们选择的距离是向后的距离,那么我们将它取反以表明我们正在从 A 向后行进到 B。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 2013-01-01
      • 2016-04-01
      • 1970-01-01
      相关资源
      最近更新 更多