简体   繁体   English

在Java语言中使用短路评估设置字符串时出现意外行为

[英]Not expected behavior while setting a string with short-circuit evaluation in Javascript

I want to use this short-circuit evaluation to report a nice status of multiple items in an one liner. 我想使用这种短路评估来报告一个衬板中多个项目的良好状态。 But the result is not as expected as shown below: 但是结果却不符合预期,如下所示:

 var items = [{ "id": 1, "available": true }, { "id": 2, "available": false }, { "id": 3, "error": "Server not found for that TLD" }]; items.forEach(function(item) { console.log(item.id, item.error || item.available ? "Available" : "Not available"); }); 

This produced the following log: 这产生了以下日志:

1 "Available"
2 "Not available"
3 "Available"

At 3 I expected it to show the error because item.error is a string and should evaluate to `true, why does it skip it to item.available? 3我希望它显示错误,因为item.error是一个字符串,应该评估为true,为什么将其跳过到item.available?

item.error || item.available item.error || item.available is truthy. item.error || item.available是真实的。

You need parentheses: 您需要括号:

item.error || (item.available ? "Available" : "Not available")

As @SLaks said parentheses will fix the problem. 正如@SLaks所说,括号将解决此问题。 The order of operations is different than you expected. 操作顺序与您预期的不同。 The || || is evaluated before the ternary operator. 在三元运算符之前进行评估。

You can see the order here. 您可以在这里查看订单。 Logical OR is just above the conditional operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence 逻辑OR刚好在条件运算符https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence之上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM