17

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.

ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
jeff
  • 13,055
  • 29
  • 78
  • 136
  • There are several negative mod solutions. http://stackoverflow.com/questions/1082917/mod-of-negative-number-is-melting-my-brain – ryan Sep 04 '13 at 15:39
  • 1
    possible duplicate of [Javascript modulo not behaving](http://stackoverflow.com/questions/4467539/javascript-modulo-not-behaving) – Vito Gentile Jun 11 '15 at 16:18
  • You should consider changing your accepted answer to the bottom one, since that one gives you an actual solution to the question asked. – M - May 11 '16 at 23:11

2 Answers2

30

You can try this :p-

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

Check out this

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
13

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.

MvG
  • 57,380
  • 22
  • 148
  • 276
  • I remember that C did not have this problem, but it was a long time ago. And I didn't know JavaScript is a descendant of C :) Thanks for your answer. – jeff Sep 04 '13 at 15:49
  • 1
    See e.g. [this poster](http://www.digibarn.com/collections/posters/tongues/ComputerLanguagesChart.png) for details on the evolution of programming languages. [The Wikipedia page](http://en.wikipedia.org/wiki/ECMAScript) lists: “Influenced by Self, HyperTalk, AWK, C, Perl, Python, Java, Scheme”. – MvG Sep 04 '13 at 16:17