根据谷歌计算器(-13)% 64 = 51。
根据Javascript(参见这个JSBin),它是-13。
我怎么解决这个问题?
根据谷歌计算器(-13)% 64 = 51。
根据Javascript(参见这个JSBin),它是-13。
我怎么解决这个问题?
当前回答
这不是一个错误,有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
其他回答
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);
}
接受的答案让我有点紧张,因为它重用了%操作符。如果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
修正负模(提醒操作符%)
简化使用ES6箭头功能,没有危险的扩展数字原型
Const mod = (n, m) => (n % m + m) % m; console.log (mod (-90, 360));// 270(不是-90)
为了好玩,这里有一个“wrap”函数,它的工作方式有点像模数,除了你也可以指定范围的最小值(而不是0):
const wrap = (value = 0, min = 0, max = 10) =>
((((value - min) % (max - min)) + (max - min)) % (max - min)) + min;
基本上就是取真模公式,对其进行偏移,使min值最终为0,然后将min值加回来。
如果有一个值希望保持在两个值之间,则很有用。