Recognizing when to use the modulus operator

前端 未结 19 917
醉梦人生
醉梦人生 2020-11-29 16:40

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?

I know I can u

19条回答
  •  迷失自我
    2020-11-29 16:52

    My favorite use is for iteration.

    Say you have a counter you are incrementing and want to then grab from a known list a corresponding items, but you only have n items to choose from and you want to repeat a cycle.

    var indexFromB = (counter-1)%n+1;

    Results (counter=indexFromB) given n=3:

    `1=1`
    `2=2`
    `3=3`
    `4=1`
    `5=2`
    `6=3`
    ...
    

提交回复
热议问题