JavaScript % (modulo) gives a negative result for negative numbers
According to Google Calculator (-13) % 64
is 51
.
According to Javascript (see this JSBin) it is -13
.
How do I fix this?
Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
};
采取这篇文章:JavaScript模块错误
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..
JavaScript中的%
运算符是余数运算符,而不是模运算符(主要区别在于如何处理负数):
-1 % 8 // -1, not 7
上一篇: 在sh脚本中计算模数