根据谷歌计算器(-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
其他回答
修正负模(提醒操作符%)
简化使用ES6箭头功能,没有危险的扩展数字原型
Const mod = (n, m) => (n % m + m) % m; console.log (mod (-90, 360));// 270(不是-90)
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
有一个NPM包可以帮你完成这项工作。您可以使用以下命令安装它。
NPM install just-modulo—save
从README复制的用法
import modulo from 'just-modulo';
modulo(7, 5); // 2
modulo(17, 23); // 17
modulo(16.2, 3.8); // 17
modulo(5.8, 3.4); //2.4
modulo(4, 0); // 4
modulo(-7, 5); // 3
modulo(-2, 15); // 13
modulo(-5.8, 3.4); // 1
modulo(12, -1); // NaN
modulo(-3, -8); // NaN
modulo(12, 'apple'); // NaN
modulo('bee', 9); // NaN
modulo(null, undefined); // NaN
GitHub存储库可以通过以下链接找到:
https://github.com/angus-c/just/tree/master/packages/number-modulo