是!! Javascript 中是否需要运算符?
我可以理解当您想要将对象值转换为布尔值并将其保存在变量中的情况。然而,我在 jQuery 模板中遇到了以下代码,并且想知道 !! (双感叹号运算符)甚至是必要的。
{{if !!sectionId}}
// do something...
{{/if}}
我假设不是,因为 Javascript 会自动将 if 后面的表达式计算为布尔值。因此,你可以写:
{{if sectionId}}
// do something...
{{/if}}
我的假设正确吗?
I can understand cases when you will want to convert an object value to a boolean and save it in a variable. However, I came across the following code in a jQuery template and was wondering if the !! (double exclamation operators) is even necessary.
{{if !!sectionId}}
// do something...
{{/if}}
I am assuming that it is not since Javascript will automatically evaluate the expression following the if as boolean. Therefore, you could just write:
{{if sectionId}}
// do something...
{{/if}}
Am I right in my assumption?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JavaScript 中没有
!!
运算符。只有!
。您所看到的是该单个运算符的双重应用程序。!
的单个应用程序将通过评估其参数的“真实性”来返回一个布尔值,并给出该值的布尔值倒数。因此,第二个!
给出了 那个 值的布尔逆,这就是原始值的布尔“真实性”。就我个人而言,我不会像您的示例一样在简单的
if
语句中使用它,但它对于可能显式检查布尔类型参数的 API 来说很方便:There is no
!!
operator in JavaScript. There's just!
. What you're seeing is a doubled application of that single operator.A single application of
!
will return a boolean by evaluating the "truthiness" of its argument, giving the boolean inverse of that. The second!
therefore gives the boolean inverse of that value, which is thus the boolean "truthiness" of the original value.Personally I wouldn't use it in a simple
if
statement as in your example, but it's handy for APIs that might explicitly check for a boolean-typed parameter: