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.

4

2 回答 2

30

你可以试试这个:p-

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

看看这个

于 2013-09-04T15:43:35.350 回答
13

如果模运算的第一个操作数是负数而第二个操作数是正数,大多数从 C 继承的语言都将返回负数结果。我不确定为什么最初做出这个决定。可能最接近当时处理器在组装中所做的。无论如何,从那时起,“为什么”的答案很可能是“因为那是懂 C 的程序员所期望的”。

MDC 参考包含一个指针,指向引入适当的mod运算符的提议。但即使这样也会保留现有的%运算符(他们称其为“余数”以更好地区分它们)并引入新的中缀词符号a mod b。该提案可追溯到 2011 年,我不知道这方面的最新进展。

于 2013-09-04T15:44:26.900 回答