检测一个Javascript变量是否真的未定义

我们如何区分var foo;var foo=undefined;

typeof foo将返回“undefined”和foo in window将返回true;


var foo意味着var foo=undefined ,除非undefined被设置undefined

这可以在浏览器控制台中看到,如果初始化一个变量但不给它一个值,它将具有undefined的值(并且类型"undefined"


我们如何区分var foo;var foo=undefined;

他们之间没有什么区别, 如果该行之前的所有使用foo 。 (不需要)JavaScript引擎可以看到var foo=undefined; 喜欢这个:

// At top of scope
var foo; // `foo` will have the value `undefined`

// Where the var foo=undefined; line was
foo = undefined;

请注意,它们是在不同时间发生的完全不同的事情。 声明和“初始化”(这实际上是一项任务)分开发生。 该声明在进入执行单位时发生; 初始化/分配稍后发生,作为逐步执行代码的一部分。 (更多:可怜的误解var

这意味着如果你有这个:

foo = 5;
alert(typeof foo); // "number"
var foo = undefined;
alert(typeof foo); // "undefined"

...这不是一个错误,因为引擎处理的方式是:

var foo;
foo = 5;
alert(typeof foo); // "number"
foo = undefined;
alert(typeof foo); // "undefined"

一个正确的例子可以创造奇迹:

function winFoo() {
  console.log('foo' in window);
}

function startFoo() {
  window.foo = 'bar';
}

function ovrFoo() {
  window.foo = undefined;
}

function removeFoo() {
  delete window.foo;
}

//window.foo === undefined
//window.foo hasn't been defined yet
winFoo(); //false
//so it makes sense that 'foo' is not in window
startFoo(); //window.foo === 'bar'
//window.foo has now been set to 'bar'
winFoo(); //true
//so it makes sense that 'foo' is in window
ovrFoo(); //window.foo === undefined
//window.foo has been overridden with a value of undefined
winFoo(); //true
//but the key 'foo' still exists in window, it just has a value of undefined
removeFoo(); //window.foo === undefined
//the key 'foo' has been removed from window and its value is therefor forgotten
winFoo(); //false
//so it makes sense that 'foo' is not in window

这是一个小提琴

另外,在任何函数上下文之外声明var foo实例化window.foo ,其值为undefined如果!('foo' in window) (意思是说,如果在同一代码块中多次调用var foo ,它不会覆盖现有的价值如果有的话)。 更重要的是, varfunction语句实际上被提升到它们范围的顶部,这意味着:

console.log('foo' in window);
var foo;
console.log('foo' in window);

将打印true而不是两次false ,然后true

链接地址: http://www.djcxy.com/p/76369.html

上一篇: Detecting if a Javascript variable is really undefined

下一篇: jQuery conditional chaining