根据谷歌计算器(-13)% 64 = 51。

根据Javascript(参见这个JSBin),它是-13。

我怎么解决这个问题?


当前回答

接受的答案让我有点紧张,因为它重用了%操作符。如果Javascript在未来改变了行为呢?

下面是一个不重用%的解决方案:

function mod(a, n) {
    return a - (n * Math.floor(a/n));
}

mod(1,64); // 1
mod(63,64); // 63
mod(64,64); // 0
mod(65,64); // 1
mod(0,64); // 0
mod(-1,64); // 63
mod(-13,64); // 51
mod(-63,64); // 1
mod(-64,64); // 0
mod(-65,64); // 63

其他回答

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

摘自本文:JavaScript Modulo Bug

使用数字。prototype很慢,因为每次你使用prototype方法时,你的数字都被包裹在一个Object中。而不是这样:

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

Use:

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

参见:https://jsperf.app/negative-modulo/2

比使用原型快97%。当然,如果业绩对你来说很重要的话。

如果x是整数,而n是2的幂,则可以使用x & (n - 1)而不是x % n。

> -13 & (64 - 1)
51 

修正负模(提醒操作符%)

简化使用ES6箭头功能,没有危险的扩展数字原型

Const mod = (n, m) => (n % m + m) % m; console.log (mod (-90, 360));// 270(不是-90)

我还要处理négative a和- n

 //best perf, hard to read
   function modul3(a,n){
        r = a/n | 0 ;
        if(a < 0){ 
            r += n < 0 ? 1 : -1
        }
        return a - n * r 
    }
    // shorter code
    function modul(a,n){
        return  a%n + (a < 0 && Math.abs(n)); 
    }

    //beetween perf and small code
    function modul(a,n){
        return a - n * Math[n > 0 ? 'floor' : 'ceil'](a/n); 
    }