英文:
Logical OR condition interpretation
问题
以下是您要翻译的内容:
Using JavaScript code below it should print the same result, but it doesn't. Using logical OR for both of the statements, the interpreter -according to my experience- it should return immediately after checking the 1st condition as soon as it finds it true. This is not the case in the example below.
Can someone explain this? Y works as expected but X does not. So, how JavaScript interpreter "decode" the X statement?
function test() {
var x = 5 || true ? 100 : 1000;
var y = 5 || (true ? 100 : 1000);
console.log(x); //returns 100
console.log(y); //returns 5
};
test();
英文:
Using JavaScript code below it should print the same result, but it doesn't. Using logical OR for both of the statements, the interpreter -according to my experience- it should return immediately after checking the 1st condition as soon as it finds it true. This is not the case in the example below.
Can someone explain this? Y works as expected but X does not. So, how JavaScript interpreter "decode" the X statement?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function test() {
var x = 5 || true ? 100 : 1000;
var y = 5 || (true ? 100 : 1000);
console.log(x); //returns 100
console.log(y); //returns 5
};
test();
<!-- end snippet -->
答案1
得分: 0
逻辑或运算符比条件运算符具有更高的优先级。因此,对于 x
的表达式等效于
var x = (5 || true) ? 100 : 1000;
由于 (5 || true)
是真值,条件运算符返回 100
。
英文:
The logical or operator has higher precedence than the conditional operator. So the expression for x
is equivalent to
var x = (5 || true) ? 100 : 1000;
Since (5 || true)
is truthy, the conditional operator returns 100
.
答案2
得分: 0
在第一个例子中,它检查是否为 5 || true
?如果是,三元运算符的结果为真,生成 100。您可以通过研究 "运算符优先级" 了解更多相关信息。
第一行的写法也不太好,你应该加上括号,以使你的意图更加明确。
换句话说,第一个例子实际上是在执行 var x = (5 || true) ? 100 : 1000;
,而 5 || true
的结果是 5,它是一个真值。
英文:
In the first one, it's checking "is 5 || true
? If so, the ternary evaluates to true, producing 100. You can learn more about this by researching "operator precedence".
The first line is also bad practice, you should include the parenthesis, to make it more clear what your intent is.
Said another way, the first one is doing var x = (5 || true) ? 100 : 1000;
, and 5 || true
evaluates to 5 which is truthy.
答案3
得分: 0
它将运行为(5 || true) ? 100 : 1000
;
你可以在这里找到||
操作符的优先级大于条件运算符?
的信息。
英文:
it will run as (5 || true) ? 100 : 1000
;
you can find here that operator ||
has precedence greater than conditional ?
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论