JavaScript % (modulo) gives a negative result for negative numbers

前端 未结 11 1342
死守一世寂寞
死守一世寂寞 2020-11-22 11:01

According to Google Calculator (-13) % 64 is 51.

According to Javascript (see this JSBin) it is -13.

How do I fix this

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 11:55

    If x is an integer and n is a power of 2, you can use x & (n - 1) instead of x % n.

    > -13 & (64 - 1)
    51 
    

提交回复
热议问题