我正在通读 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/