[英]Mathematical Operator over Boolean values in JavaScript
Can someone explain what will be the order of execution of following JavaScript Code: 有人可以解释以下JavaScript代码的执行顺序:
(true + false) > 2 + true
I understand using + operator over two Boolean values returns the result as 0,1 or 2 depending upon the values being provided. 我知道对两个布尔值使用+运算符会根据提供的值将结果返回为0,1或2。
I interpreted output of above code as 1 by breaking the execution in following order: 我通过按以下顺序中断执行将上述代码的输出解释为1:
1) (true + false) // Outputs : 1
2) 1 > 2 // Outputs : false
3) false + true //Outputs : 1
But the actual result is: 但是实际结果是:
false
Can anyone correct my understanding if am interpreting the code in wrong way. 如果以错误的方式解释代码,谁能纠正我的理解。
Your 2nd
point is not correct. 您的
2nd
点是不正确的。
1) (true + false) outputs - 1
2) (2 + true) - outputs 3
3) 1 > 3 - outputs false
You can check this using functions 您可以使用功能检查
(true + false) > 2 + true function f1() { const cond = true + false; console.log(cond); return cond; } function f2() { const cond = 2 + true; console.log(cond); return cond; } console.log(f1() > f2());
If you want to compare with 2 then add true, you must to wrap into the parentheses 如果要与2进行比较,然后加上true,则必须用括号括起来
((true + false) > 2) + true
What you have is a question of operator precedence , of three parts, 您所拥有的是运算符优先级的问题,分为三个部分,
( ... )
grouping with the highest precedence of 20, ( ... )
分组的最高优先级为20,
>
greater than (here) with the lowest precendece of 11. >
大于 (这里)具有最低的11。
That means the operators with higer precedence are evaluated first and the comes the once with lower precedence. 这意味着优先级较高的运算符将首先被评估,而优先级较低的运算符将被优先评估。
(true + false) > 2 + true
(true + false) -> 1
2 + true -> 3
1 > 3 -> false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.