最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I reset my counter when it gets to the end of my array? - Stack Overflow

programmeradmin2浏览0评论

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: /

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/nTmu7/2/

Share Improve this question edited Dec 24, 2015 at 3:38 Yeldar Kurmangaliyev 34.2k13 gold badges64 silver badges104 bronze badges asked Dec 24, 2015 at 3:37 MikeMike 6387 silver badges21 bronze badges 2
  • 1 Where is your array and "displays the contents of the array"? Now, it only sets the integer content. – Yeldar Kurmangaliyev Commented Dec 24, 2015 at 3:38
  • count = count % myArray.length – Andreas Louv Commented Dec 24, 2015 at 3:41
Add a ment  | 

3 Answers 3

Reset to default 7

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./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/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

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;
}

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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>a</button>

发布评论

评论列表(0)

  1. 暂无评论