使用百分比符号进行比较? %的JavaScript
当简化我的代码,堆栈溢出用户改变了这一行代码:使用百分比符号进行比较? %的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
所以它是字面意义上只是将地点的价值除以序列的长度,然后将余数分配给地方? – AntsOfTheSky
正确@HeatherLara –
的%
符号在大多数编程语言,包括JavaScript使用,Modulu。
modulo是用于查找一个数字除以另一个数字后的余数的操作用法。
例如:
7%3 = 1
10%2 = 0
9%5 = 4
它是reminder operator %
,不模运算符,它的Javascript实际上没有。
余(%)
求余运算符返回余遗留当一个操作数是由第二操作数划分。它始终是股利的标志,而不是除数。它使用内置的模函数来产生结果,该结果是将
var1
除以var2
的整数余数 - 例如 -var1
模var2
。 There is a proposal to get an actual modulo operator in a future version of ECMAScript,不同之处在于模运算符的结果将取除数的符号,而不是股息。
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; }
凡严格的定义,我觉得最好引用[* ECMA-262 *](http://ecma-international.org/ecma-262/7.0/index.html#sec-applying-the -mod-operator):“*%MultiplicativeOperator从隐含的分区中产生其操作数的余数;左操作数是被除数,右操作数是除数......浮点余数操作的结果由%运算符不同于IEEE 754-2008定义的“余数”运算。*“所以它不是严格的”余数运算符“。 ;-) – RobG
看一看[此](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators) – m87