You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 counter is 0: (0 + 1) % 3 = 1 → displays "B"
  • When counter is 1: (1 + 1) % 3 = 2 → displays "C"
  • When counter is 2: (2 + 1) % 3 = 0 → resets to 0, displays "A"
  • This cycle repeats indefinitely without needing an explicit if check.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:42:56