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.
(%) 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
byvar2
— for example —var1
modulovar2
. 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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.