Endlessly moving through an array backwards
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
.
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.
Yes, you could use a single formula for both forwards
and backwards
by creating a common function move
and pass the step
as parameter.
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>