问题
If I have the following code
var num = 15 % 2 + 6 * 4;
for example... I'd like to know what the output will be, specifically I would like to know the order of precedence for modulus (the operation executed by the %
symbol). Will the modulus be performed before or after the addition and multiplication operations?
Edit: I have already looked at the article people are linking me to
MDN Operator Precedence
And had done so before asking the question, but unfortunately it didn't contain enough information to completely answer my question, hence my asking here. Just to save people the effort of linking again.
Update: Looking into associativity as indications from discussion in the comments beneath one proposed answer are that the question is associated with associativity (if you'll pardon the accidental pun).
Update: Syntax edit (^_^?)
回答1:
Technically it's the remainder operator (more mathematical minds than mine say modulus would handle sign differences differently), and it has the same precedence and associativity as multiplication and division.
So
var num = 15 % 2 + 6 * 4;
is
var num = (15 % 2) + (6 * 4);
MDN has a handy article on operator precedence and associativity.
Re your comment on the question:
...I get the
num
variable value of25
with the example code, yetvar num = 3 * 15 % 2 + 6 * 4;
also results in anum
variable which aconsole.log
shows as also bearing the value of25
...
That's because both 15 % 2 + 6 * 4
and 3 * 15 % 2 + 6 * 4
are 25
. Let's break it down:
Your first example: 15 % 2 + 6 * 4
15 % 2 + 6 * 4
1 + 6 * 4
1 + 24
25
Your second example: 3 * 15 % 2 + 6 * 4
3 * 15 % 2 + 6 * 4
45 % 2 + 6 * 4
1 + 6 * 4
1 + 24
25
回答2:
Basically you going left to right but you're doing plus first, then multiply, then divide, and the remainder stuff is divide. So
var num = 15 % 2 + 6 * 4;
is basically 15 % 2 = 1
回答3:
Modulo should have the same precedence as division, multiplication, and exponents. See here
来源:https://stackoverflow.com/questions/36087166/what-is-the-order-of-precedence-for-modulus-in-javascript