如何在JavaScript中计算负整数的模数? [英] How to calculate modulo of negative integers in JavaScript?

查看:105
本文介绍了如何在JavaScript中计算负整数的模数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试迭代jQuery对象数组,通过递增或递减1.因此,对于递减部分,我使用此代码:

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];

所以我有4个带id的元素:

so I have 4 elements with id's:

div_0
div_1
div_2
div_3

我期待它迭代为
3 - 2 - 1 - 0 - 3 - 2 - 等..

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

但它返回零后的-1,因此它被卡住了。所以它迭代为:

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

3 - 2 - 1 - 0 - -1 - 卡住

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;

但我想知道为什么JavaScript不计算负模型。也许这也会帮助另一个程序员。

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

推荐答案

你可以试试这个:p -

You can try this :p-

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

查看这个

这篇关于如何在JavaScript中计算负整数的模数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆