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

前端 未结 11 1468
死守一世寂寞
死守一世寂寞 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 12:03

    Using Number.prototype is SLOW, because each time you use the prototype method your number is wrapped in an Object. Instead of this:

    Number.prototype.mod = function(n) {
      return ((this % n) + n) % n;
    }
    

    Use:

    function mod(n, m) {
      return ((n % m) + m) % m;
    }
    

    See: http://jsperf.com/negative-modulo/2

    ~97% faster than using prototype. If performance is of importance to you of course..

提交回复
热议问题