Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mod to wrap around

Assume the array has a length of 1000. I am trying to create a simple way to traverse the image paths stored in the array without going out of bounds. The method below handles the wrap around using modulus well when it comes to clicking the 'next' button to increment array index, but not when I have to decrement and deduct one from the index (when the user clicks the previous button).

Basically what I am trying to do is:

998 -> click next -> 999
999 -> click next -> 0
0 -> click previous -> 999

My Javacript

var index = 0;

$('.catalog-img-container').attr("src", javascript_array[index]);
$(".next").click(function(){
        $('.catalog-img-container').attr("src", javascript_array[++index%arrayLength]);
    });         
$(".previous").click(function(){
    $('.catalog-img-container').attr("src", javascript_array[--index]);
    alert(index);

I appreciate any help with

Many thank in advance.

like image 792
AnchovyLegend Avatar asked Jan 14 '13 20:01

AnchovyLegend


People also ask

What does mod mean in math?

The modulo (or "modulus" or "mod") is the remainder after dividing one number by another. Example: 100 mod 9 equals 1. Because 100/9 = 11 with a remainder of 1. Another example: 14 mod 12 equals 2. Because 14/12 = 1 with a remainder of 2.

How do you do modulus in Python?

The Python modulo operator calculates the remainder of dividing two values. This operator is represented by the percentage sign (%). The syntax for the modulo operator is: number1 % number2. The first number is divided by the second then the remainder is returned.

How does a modulo operator work?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.


1 Answers

There might be a more elegant way around this, but this is simple:

$(".previous").click(function(){
    if (--index < 0) index = arrayLength - 1;
    $('.catalog-img-container').attr("src", javascript_array[index%arrayLength]);
}); 
like image 95
Shmiddty Avatar answered Sep 27 '22 21:09

Shmiddty