[英]How come my value gets reset to 0 when I change screen if I am using async storage?
[英]How do I reset my counter when it gets to the end of my array?
我有一个按钮,它在单击时遍历数组并显示数组的内容。 当我到达数组的末尾时,我想将计数器设置回开头。 到目前为止,这是我的代码:
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);});
工作演示: http : //jsfiddle.net/nTmu7/2/
使用 Reminder 运算符 ( AKA: Modulus) %
循环数组
counter = (counter + 1) % array.length;
例子:
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>
重读总是好的: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
通过数组的大小对计数器进行模数。 即我 % array.length 会让你回到 0。如果我等于长度。 我通常有一个 if 语句。
喜欢
if(I == array.length){
I %= array.length;
}
您可以简单地使用模数 ( %
)。
按数组的长度取模可确保您永远不会超过它:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.