简体   繁体   English

无休止地向后移动数组

[英]Endlessly moving through an array backwards

I've got to be able moving through an array forwards and backwards.我必须能够前后移动数组。 Endlessly and without getting an index out of bounds-exception.无休止地并且不会使索引越界异常。

For moving forward I've known an elegant way using the modulo-operator.为了继续前进,我知道使用模运算符的一种优雅方式。 For the backwards moving I've had to figure out something myself.对于向后移动,我不得不自己想办法。

Here's my solution:这是我的解决方案:

 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]); });
 <!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>

It works.有用。 But is there a more elegant solution for moving backwards?但是有没有更优雅的后退解决方案?

So that one can get rid of this ugly if-check.这样就可以摆脱这个丑陋的 if-check。

You can still use the modulus operator.您仍然可以使用模运算符。 To go backwards, it'd be要倒退,那就是

i = (i - 1 + array.length) % array.length;

When i is 0, the partial result will be (0 - 1 + array.length) , which is array.length - 1 .i为 0 时,部分结果将为(0 - 1 + array.length) ,即array.length - 1

For any value greater than 0 but less than array.length , the modulus operator maps the value greater than array.length to the correct index in range.对于任何大于 0 但小于array.length的值,模数运算符将大于array.length的值映射到范围内的正确索引。

Yes, you could use a single formula for both forwards and backwards by creating a common function move and pass the step as parameter.是的,您可以通过创建一个通用函数move并将step作为参数传递给forwardsbackwards使用单个公式。

i = (i + step + arr.length ) % arr.length; 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]); }
 <button id="inc" onclick="move(1)">Inc</button> <button id="dec" onclick="move(-1)">Dec</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM