JS新手求助:如何用%运算符替代if语句重写代码块
Using the Modulo Operator to Simplify Your Counter Reset Logic
Hey there! Great call looking to use the modulo (%) operator here—it’s a clean, concise way to replace that if statement for cycling through your array.
The modulo operator returns the remainder when one number is divided by another. For your use case, since you want to loop through an array of length 3, every time the counter would hit 3 (the array’s length), counter % 3 will automatically give 0—exactly the reset behavior you need.
Here’s your rewritten code with this approach:
<!DOCTYPE html> <html> <head> <script> window.onload=function(){ var letters = ["A","B","C"]; var counter = 0; var timer=setInterval( function(){ // Modulo handles the reset automatically counter = (counter + 1) % letters.length; document.getElementById("demo").value = letters[counter]; }, 1000); } </script> </head> <body> <input type="text" id="demo" value="A"> </body> </html>
Breakdown of the change:
- When
counteris 0:(0 + 1) % 3 = 1→ displays "B" - When
counteris 1:(1 + 1) % 3 = 2→ displays "C" - When
counteris 2:(2 + 1) % 3 = 0→ resets to 0, displays "A" - This cycle repeats indefinitely without needing an explicit
ifcheck.
I also added a few semicolons and line breaks for readability—small tweaks that make the code easier to follow without changing its behavior.
内容的提问来源于stack exchange,提问作者NYGuide
相关产品推荐
相关产品推荐

