Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reset my counter when it gets to the end of my array?

I have a button that iterates through an array on click and displays the contents of the array. When I get to the end of the array, I would like to set the counter back to the beginning. Here is my code so far:

HTML:

<div id="likes">
<span class="figure">
</span>
</div>
<button type="button" id="like" >Like</button>

JavaScript:

var clicks = 0; $("#like").click(function(){ clicks++; 
$('.figure').html(clicks);});

working demo: http://jsfiddle.net/nTmu7/2/

like image 788
Mike Avatar asked Dec 24 '15 03:12

Mike


3 Answers

Use the Reminder operator (AKA: Modulus) % to loop your array

counter = (counter + 1) % array.length;

Example:

var array = ["One", "Two", "Three"];
var counter = 0;

$("#like").click(function(){
  $('#likes').text( array[counter] );
  counter = ++counter % array.length;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="like">LOOP ARRAY</button>
<div id="likes"></div>

Always good to re-read: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

like image 63
Roko C. Buljan Avatar answered Nov 19 '22 04:11

Roko C. Buljan


Modulus the counter by the size of the array. I.e. I % array.length will get you back to 0. If I equals the length. I normally have an if statement.

Like

if(I == array.length){
    I %= array.length;
}
like image 29
Caperneoignis Avatar answered Nov 19 '22 05:11

Caperneoignis


You can simply use modulo (%).
Taking the modulo by length of an array guarantees that you never excced it:

var ind = 0;
var val = ['a', 'b', 'c'];

$("button").on('click', function() {
  ind = (ind + 1) % val.length; // or "ind++; ind %= val.length;"
  $(this).text(val[ind]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>a</button>
like image 2
Yeldar Kurmangaliyev Avatar answered Nov 19 '22 06:11

Yeldar Kurmangaliyev