我现在正在阅读“发现流星”,在第 7 章中有代码:
Posts.allow({
insert: function(userId, doc) {
// only allow posting if you are logged in
return !! userId; ///// <<==== what does "!!" means?
}
});
谢谢
我现在正在阅读“发现流星”,在第 7 章中有代码:
Posts.allow({
insert: function(userId, doc) {
// only allow posting if you are logged in
return !! userId; ///// <<==== what does "!!" means?
}
});
谢谢
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);
因此将转换为布尔值,然后进行双重否定
!会将任何正值、真值或现有变量(如字符串和数组)变为假,并将任何负值、未定义、空或假变为真。!!应用它两次。
在这种情况下,如果变量 userId 存在并且不为空、null 或 false,它将返回 true。
它就像您将变量类型更改为布尔值
!! userId;
// same as
userId ? true:false;