javascript - 为什么 !在函数不返回相反的 bool 值之前?

标签 javascript iife

我正在通读 this SO question .我有点明白发生了什么,但我很困惑为什么

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

不返回 false

!function () {}() This will also return the boolean opposite of the return value of the function, in this case true, because !undefined is true. If you want the actual return value to be the result of the call, then try doing it this way:

“还将返回相反的 bool 值”让我认为应该返回 false。为什么不是呢。 警报(!真);//假

最佳答案

如果没有 return 语句,该函数将返回 undefined。当您将 ! 应用于 undefined 时,您会得到 true

尝试

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

请注意,在 IIFE 之前惯用的 ! 就是一个惯用语。 ! 运算符对返回值有影响这一事实几乎总是无关紧要,因为调用环境完全忽略了返回值。因此

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

实际上完全相同,即使 + 一元运算符与 ! 一元运算符不同。

关于javascript - 为什么 !在函数不返回相反的 bool 值之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25585419/

相关文章:

c# - 匹配美元金额的正则表达式

swift - Swift 中 IIFE 的类型推断

函数表达式前面的 JavaScript 加号

javascript - 在 XSL 中处理 HTML 标签

javascript - 禁用其他 Bootstrap-datepicker View 模式?

javascript - 立即函数调用语法

javascript - 箭头函数(它是一个参数)如何接受 x 的值作为 1 并返回它?

javascript - 从开发者工具访问 IIFE 变量

javascript - SpeechSynthesisUtterance Chrome 问题

javascript - 带有 Javascript 的条纹表 DOM