How to calculate modulo of negative integers in JavaScript?

本秂侑毒 提交于 2019-12-08 14:45:59

问题


I'm trying to iterate over an array of jQuery objects, by incrementing or decrementing by 1. So, for the decrementing part, I use this code:

var splitted_id = currentDiv.attr('id').split('_');
var indexOfDivToGo = parseInt(splitted_id[1]);
indexOfDivToGo = (indexOfDivToGo-1) % allDivs.length;
var divToGo = allDivs[indexOfDivToGo];

so I have 4 elements with id's:

div_0
div_1
div_2
div_3

I was expecting it to iterate as 3 - 2 - 1 - 0 - 3 - 2 - etc..

but it returns -1 after the zero, therefore it's stuck. So it iterates as:

3 - 2 - 1 - 0 - -1 - stuck

I know I can probably fix it by changing the second line of my code to

indexOfDivToGo = (indexOfDivToGo-1 + allDivs.length) % allDivs.length;

but I wonder why JavaScript is not calculating negative mods. Maybe this will help another coder fellow too.


回答1:


You can try this :p-

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

Check out this




回答2:


Most languages which inherit from C will return a negative result if the first operand of a modulo operation is negative and the second is positive. I'm not sure why this decision was made originally. Probably closest to what processors at that time did in assembly. In any case, since then the answer to “why” is most likely “because that's what programmers who know C expect”.

The MDC Reference contains a pointer to a proposal to introduce a proper mod operator. But even that would keep the existing % operator (which they call “remainder” to better distinguish between them) and introduce a new infix word notation a mod b. The proposal dates from 2011, and I know no more recent developments in this direction.



来源:https://stackoverflow.com/questions/18618136/how-to-calculate-modulo-of-negative-integers-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!