简体   繁体   English

Javascript 简写语法解释

[英]Javascript shorthand syntax explanation

I gone through this syntax in my project.我在我的项目中经历了这种语法。 Can I get the explanation for this code please?我可以得到这个代码的解释吗?

 // Handles focus on error title.
 var error = $('#consentError')[0];
 error && error.focus();

Is this the shorthand syntax for if() condition.这是 if() 条件的简写语法。

Yes, the code is equivalent to是的,代码相当于

var error = $('#consentError')[0];
if (error) {
  error.focus();
}

The if version is definitely easier to read and comprehend at a glance. if版本绝对更容易一目了然地阅读和理解。 Using the && method creates an unused expression, which is weird and is often forbidden by linters.使用&&方法会创建一个未使用的表达式,这很奇怪并且通常被 linter 禁止

But jQuery has an even better way to achieve this - just call focus on the jQuery collection, and it'll call .focus() on the native element, if there is such an element (and if there isn't one, it just won't do anything - it won't throw).但是 jQuery 有一个更好的方法来实现这一点 - 只需调用 jQuery 集合上的focus ,它会调用.focus()对本机元素,如果有这样一个元素(如果没有,它只是不会做任何事情 - 它不会抛出)。

$('#consentError').focus();

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

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