繁体   English   中英

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

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

我想使用这种短路评估来报告一个衬板中多个项目的良好状态。 但是结果却不符合预期,如下所示:

 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"); }); 

这产生了以下日志:

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

3我希望它显示错误,因为item.error是一个字符串,应该评估为true,为什么将其跳过到item.available?

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

您需要括号:

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

正如@SLaks所说,括号将解决此问题。 操作顺序与您预期的不同。 || 在三元运算符之前进行评估。

您可以在这里查看订单。 逻辑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