最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

variables - Comparing using a percentage sign? % JavaScript - Stack Overflow

programmeradmin0浏览0评论

When simplifying my code, a stack overflow user changed this line of code:

if (place > sequence.length -1) {
    place = 0;

to this:

 place = place % sequence.length;

and I'm wondering what this line actually does and how you would define the use of this line and the use of the percentage sign. Thanks for help in advance.

When simplifying my code, a stack overflow user changed this line of code:

if (place > sequence.length -1) {
    place = 0;

to this:

 place = place % sequence.length;

and I'm wondering what this line actually does and how you would define the use of this line and the use of the percentage sign. Thanks for help in advance.

Share Improve this question asked Feb 25, 2017 at 20:58 AntsOfTheSkyAntsOfTheSky 2052 gold badges4 silver badges18 bronze badges 2
  • take a look at this – m87 Commented Feb 25, 2017 at 21:01
  • Better here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Michel Moraes Commented Aug 29, 2020 at 12:01
Add a comment  | 

3 Answers 3

Reset to default 9

(%) is the modulus operator, it will let you have the remainder of place/sequence.length.

5 % 1 = 0 // because 1 divides 5 (or any other number perfectly)
10 % 3 = 1 // Attempting to divide 10 by 3 would leave remainder as 1

The % symbol is used in most programming languages, including JavaScript, as Modulu.

modulo is the operation use to find the remainder after division of one number by another.

For example:

7 % 3 = 1

10 % 2 = 0

9 % 5 = 4

It is the remainder operator %, not the modulo operator, which Javascript actually does not have.

Remainder (%)

The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.

console.log(-4 & 3);
console.log(-3 & 3);
console.log(-2 & 3);
console.log(-1 & 3);
console.log(0 & 3);
console.log(1 & 3);
console.log(2 & 3);
console.log(3 & 3);
.as-console-wrapper { max-height: 100% !important; top: 0; }

发布评论

评论列表(0)

  1. 暂无评论