根据谷歌计算器(-13)% 64 = 51。
根据Javascript(参见这个JSBin),它是-13。
我怎么解决这个问题?
根据谷歌计算器(-13)% 64 = 51。
根据Javascript(参见这个JSBin),它是-13。
我怎么解决这个问题?
当前回答
如果x是整数,而n是2的幂,则可以使用x & (n - 1)而不是x % n。
> -13 & (64 - 1)
51
其他回答
使用数字。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%。当然,如果业绩对你来说很重要的话。
Number.prototype.mod = function (n) {
"use strict";
return ((this % n) + n) % n;
};
摘自本文:JavaScript Modulo Bug
我还要处理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);
}
这不是一个错误,有3个函数来计算模,你可以使用一个适合你的需要(我建议使用欧几里得函数)
截断小数部分函数
console.log( 41 % 7 ); // 6
console.log( -41 % 7 ); // -6
console.log( -41 % -7 ); // -6
console.log( 41 % -7 ); // 6
整部函数
Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
};
console.log( parseInt( 41).mod( 7) ); // 6
console.log( parseInt(-41).mod( 7) ); // 1
console.log( parseInt(-41).mod(-7) ); // -6
console.log( parseInt( 41).mod(-7) ); // -1
欧几里得函数
Number.prototype.mod = function(n) {
var m = ((this%n)+n)%n;
return m < 0 ? m + Math.abs(n) : m;
};
console.log( parseInt( 41).mod( 7) ); // 6
console.log( parseInt(-41).mod( 7) ); // 1
console.log( parseInt(-41).mod(-7) ); // 1
console.log( parseInt( 41).mod(-7) ); // 6
一个“mod”函数,返回一个正的结果。
var mod = function (n, m) {
var remain = n % m;
return Math.floor(remain >= 0 ? remain : remain + m);
};
mod(5,22) // 5
mod(25,22) // 3
mod(-1,22) // 21
mod(-2,22) // 20
mod(0,22) // 0
mod(-1,22) // 21
mod(-21,22) // 1
当然
mod(-13,64) // 51