简体   繁体   English

为什么呢! 一个函数之前不返回布尔相反的值?

[英]Why does a ! before a function not return boolean opposite value?

I was reading through this SO question . 我正在阅读这个SO问题 I sort of understand what's going on, but I'm confused why 我有点理解发生了什么,但是我很困惑为什么

!function foo() {
  console.log(true) ;
}()

doesn't return false . 不返回false

!function () {}() This will also return the boolean opposite of the return value of the function, in this case true, because !undefined is true. !function () {}()这还将返回与函数返回值相反的布尔值,在本例中为true,因为!undefined为true。 If you want the actual return value to be the result of the call, then try doing it this way: 如果您希望实际的返回值是调用的结果,请尝试通过以下方式进行操作:

"will also return the boolean opposite" makes me think that false should be returned. “也将返回布尔值相反的值”使我认为应该返回false Why isn't it. 为什么不呢 alert(!true); //false

Without a return statement the function returns undefined . 如果没有return语句,该函数将返回undefined When you apply ! 当您申请! to undefined you get true . undefined您将得到true

Try 尝试

console.log(!function() { return true; }());

Note that the idiomatic use of ! 注意,习惯用法! before an IIFE is just that — an idiom. 在IIFE之前就是这样-一个成语。 The fact that the ! 事实! operator has an effect on the return value almost always doesn't matter, because the return value is being completely ignored by the calling environment. 运算符对返回值几乎没有影响,因为返回值被调用环境完全忽略了。 Thus 从而

+function() {
  // whatever
}();

is effectively exactly the same, even though the + unary operator is different from the ! 实际上,即使+一元运算符不同于! ,它实际上也是完全相同的! unary operator. 一元运算符。

Functions that have either an empty return statement or a non-existent one return the value undefined upon their invocation. 具有空return语句或不存在的return语句的函数在调用时将返回未定义的值。 Applying ! 正在申请! to "falsy" values such as 0, null, undefined return true. 设置为“虚假”值(例如0,null,undefined)将返回true。

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

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