[英]What's the reason to make a conditional without a result?
I came across this code: 我遇到了这段代码:
navigation.on('click', '.main-nav-item', function (e) {
var clickedNavItem = $j(this),
className = clickedNavItem.data('class'),
midNavItem = $j('.' + className, midNavigation);
midNavItem.length > 0 && e.preventDefault();
});
I try to understand the purpose of the last row: 我试着理解最后一行的目的:
midNavItem.length > 0 && e.preventDefault();
It seems to stop the click if midNavItem.Length > 0, but I don't under stand the syntax of this. 如果midNavItem.Length> 0,它似乎停止了点击,但我没有遵守这个的语法。 It ought to be_
它应该是_
if(midNavItem.length > 0) { e.preventDefault() };
Not two conditionals. 不是两个条件。
Why would you write it like this? 你为什么这样写?
It's known as short-circuit evaluation . 它被称为短路评估 。 You are correct – it is another way of writing the
if
statement you suggested: 你是对的 - 这是写你建议的
if
语句的另一种方式:
if (midNavItem.length > 0) {
e.preventDefault();
}
It works because &&
won't execute the second operand unless the first is truthy . 它的工作原理是因为
&&
不会执行第二个操作数,除非第一个操作数是真的 。
The rationale for using it is typically to make for neater code. 使用它的基本原理通常是制作更整洁的代码。 This, of course, is subjective.
当然,这是主观的。 There are probably people who say it is always better to explicitly use the
if
syntax – but you will also find a number of people / popular libraries using the shorthand extensively. 可能有人说明确使用
if
语法总是更好 - 但是你也会发现很多人/流行的库使用简写。
It's shorter. 它更短。
Although in this case that "shortness" is lost by the large amounts of whitespace. 尽管在这种情况下,大量的空格会丢失“短促”。
This is the kind of optimisation that should only be done by a minifying program, not manually, because it makes the code less readable. 这种优化只能通过缩小程序来完成, 而不是手动完成,因为它会降低代码的可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.