无休止地向后移动数组

mic*_*ech 6 javascript arrays algorithm

我必须能够前后移动数组。无休止地并且不会使索引越界异常。

为了继续前进,我知道使用模运算符的一种优雅方式。对于向后移动,我不得不自己想办法。

这是我的解决方案:

const inc = document.getElementById("inc");
const dec = document.getElementById("dec");
const arr = ["One", "Two", "Three", "Four", "Five", "Six"];
let i = 0;

inc.addEventListener("click", () => {
  i = (i + 1) % arr.length;

  console.log(arr[i]);
});

dec.addEventListener("click", () => {
  i = i - 1;

  if (i === -1) {
    i = arr.length - 1;
  }

  console.log(arr[i]);
});
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <button id="inc">Inc</button>
  <button id="dec">Dec</button>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

有用。但是有没有更优雅的后退解决方案?

这样就可以摆脱这个丑陋的 if-check。

Poi*_*nty 6

您仍然可以使用模运算符。要倒退,那就是

i = (i - 1 + array.length) % array.length;
Run Code Online (Sandbox Code Playgroud)

i为 0 时,部分结果将为(0 - 1 + array.length),即array.length - 1

对于大于 0 但小于 的任何值array.length,模数运算符将大于的值映射array.length到范围内的正确索引。


Mih*_*nut 5

是的,你可以使用一个单一的公式都forwardsbackwards通过创建一个共同的功能,move并通过step作为参数。

i = (i + step + arr.length ) % arr.length;

let arr = ["One", "Two", "Three", "Four", "Five", "Six"] , i = 0
function move(step){
  i = (i + step + arr.length ) % arr.length;
  console.log(arr[i]);
}
Run Code Online (Sandbox Code Playgroud)
<button id="inc" onclick="move(1)">Inc</button>
<button id="dec" onclick="move(-1)">Dec</button>
Run Code Online (Sandbox Code Playgroud)