看下面的代码,我不明白 (typeof a !== 'undefined') 是如何工作的。我知道变量“a”不在 IIFE 内部,所以它在外部是未定义的。但是我不明白代码是如何打印出 'false'
(function(){
var a = 3;
})();
console.log("a defined? " + (typeof a !== 'undefined'));
//prints false- but how and why?
如果我删除 typeof 并只执行
console.log("a defined? " + (typeof a !== 'undefined'));
Uncaught ReferenceError: a is not defined
我收到一条错误消息,提示 Uncaught ReferenceError: a is not defined。那么,当存在 typeof 时它如何运行良好 - 而当 typeof 被删除时它会出错?这是我的困惑
最佳答案
如您所说,a
不存在于 IFFE 之外。因此,它在不同的范围内是未定义的。
//Enter the following in your console.
typeof a // --> "undefined"
(function(){
var a = 3;
})();
typeof a // --> "undefined" (Still)
当您检查类型时可能会出现问题,并且可能会误解 bool 值评估(这是一种双重否定)。 typeof a === 'undefined'
为 true
,因此 typeof a !== 'undefined'
为 false
.
关于javascript - 这个 Javascript 代码片段如何打印 'false' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41493540/