使用百分号比较? % JavaScript
Comparing using a percentage sign? % JavaScript
在简化我的代码时,堆栈溢出用户更改了这行代码:
if (place > sequence.length -1) {
place = 0;
对此:
place = place % sequence.length;
我想知道这条线的实际作用以及您将如何定义这条线的使用和百分号的使用。预先感谢您的帮助。
(%) 是取模运算符,它会让你得到 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
%
符号用于大多数编程语言,包括 JavaScript,如 Modulu.
模数是一个数除以另一个数后求余数的运算。
例如:
7 % 3 = 1
10% 2 = 0
9 % 5 = 4
是remainder operator %
,不是模运算符,Javascript其实没有
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; }
在简化我的代码时,堆栈溢出用户更改了这行代码:
if (place > sequence.length -1) {
place = 0;
对此:
place = place % sequence.length;
我想知道这条线的实际作用以及您将如何定义这条线的使用和百分号的使用。预先感谢您的帮助。
(%) 是取模运算符,它会让你得到 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
%
符号用于大多数编程语言,包括 JavaScript,如 Modulu.
模数是一个数除以另一个数后求余数的运算。
例如:
7 % 3 = 1
10% 2 = 0
9 % 5 = 4
是remainder operator %
,不是模运算符,Javascript其实没有
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; }