What is the order of precedence for modulus in Javascript?

半腔热情 提交于 2020-06-23 18:38:46

问题


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 of 25 with the example code, yet var num = 3 * 15 % 2 + 6 * 4; also results in a num variable which a console.log shows as also bearing the value of 25...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!