I'm wondering if there is a more effective way of circling through an array. For my purposes, the array is holding image sources. When the last image is shown and the next button is pushed it circles back to the first image. If the previous button is pushed on the first image it circles to the last image.
This is what I was able to come up with, but I feel there's a more efficient way to go about it.
var marker = 0;
// Circle through an array.
function moveMarker(array, action, direction) {
if (!direction) {
if(marker == array.length - 1)
marker = -1;
marker += 1;
action();
}
else {
if (marker == 0)
marker = array.length;
marker -=1;
action();
}
}
Yes, you can use the %
modulo operator:
var marker = 0;
// Circle through an array.
function moveMarker(array, action, direction) {
if (!direction) {
marker = (marker + 1) % array.length;
}
else {
marker = (marker + array.length - 1) % array.length;
}
action();
}
or even:
var marker = 0;
// Circle through an array.
function moveMarker(array, action, direction) {
marker = (marker + array.length + (direction ? -1 : 1)) % array.length;
action();
}
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