简体   繁体   English

这个语法是什么意思----->“ !! ”中的JavaScript?

[英]What does this syntax means -----> “ !! ” in javascript?

I am reading "Discover Meteor" at the moment, In chapter 7 is has code: 我现在正在阅读“发现流星”,在第7章中有代码:

Posts.allow({
  insert: function(userId, doc) {
    // only allow posting if you are logged in
    return !! userId;                        ///// <<==== what does "!!" means?
  }
});

Thanks 谢谢

Beautifully summed up by Tom Ritter as Tom Ritter很好地总结为

// Maximum Obscurity:
val.enabled = !!userId;

// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;

// And finally, much easier to understand:
val.enabled = (userId != 0);

therefore doing casting to a boolean and then doing double negation 因此,将其转换为布尔值,然后进行双重否定

! will turn any positive value, true, or existing variable(such as strings and arrays) into a false, and any negative, undefined, null, or false into a true. 会将所有正值,true或现有变量(例如字符串和数组)转换为false,并将任何负数,未定义,null或false转换为true。 !! applies it twice. 应用两次。

In this context it would be returning true if the variable userId exists and is not empty, null, or false. 在这种情况下,如果变量userId存在且不为空,null或false,它将返回true。

It just likes you change variable type to boolean 就像您将变量类型更改为布尔值一样

!! userId;

// same as

userId ? true:false;

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

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