Javascript中模数的优先顺序是什么? [英] What is the order of precedence for modulus in Javascript?

查看:48
本文介绍了Javascript中模数的优先顺序是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码

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 运算符优先级

并且在提出问题之前已经这样做了,但不幸的是它没有包含足够的信息来完全回答我的问题,因此我在这里提问.只是为了节省人们再次链接的工作.

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 (^_^?)

推荐答案

从技术上讲,它是 remainder 运算符(比我更多的数学头脑说模数会以不同的方式处理符号差异),并且它具有相同的优先级和结合性乘除法.

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.

所以

var num = 15 % 2 + 6 * 4;

var num = (15 % 2) + (6 * 4);

MDN 有一篇方便的文章运算符优先级和结合性.

MDN has a handy article on operator precedence and associativity.

重新您对问题的评论:

...我通过示例代码获得了 25num 变量值,但是 var num = 3 * 15 % 2 + 6 * 4; 还会产生一个 num 变量,console.log 显示该变量也带有 25...

...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...

那是因为 15 % 2 + 6 * 43 * 15 % 2 + 6 * 4 都是 25.让我们分解一下:

That's because both 15 % 2 + 6 * 4 and 3 * 15 % 2 + 6 * 4 are 25. Let's break it down:

你的第一个例子:15 % 2 + 6 * 4

15 % 2 + 6 * 4
1      + 6 * 4
1      + 24
25

你的第二个例子:3 * 15 % 2 + 6 * 4

3 * 15 % 2 + 6 * 4
45     % 2 + 6 * 4
1          + 6 * 4
1          + 24
25

这篇关于Javascript中模数的优先顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆