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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With