我们如何区分var foo;
和var foo=undefined;
?
typeof foo
将返回“undefined”,foo in window
将返回true;
答案 0 :(得分:10)
var foo
隐含var foo=undefined
,除非undefined
被设置为undefined
以外的其他内容。
这可以在浏览器控制台中看到,如果您初始化变量但没有给它一个值,它将具有值undefined
(以及类型"undefined"
)
答案 1 :(得分:2)
我们如何区分
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;
请注意,它们是在不同时间发生的完全不同的事情。声明和“初始化”(它实际上是一个赋值)分别发生 。声明在进入执行单位时发生;初始化/分配稍后发生,作为逐步执行代码的一部分。 (更多:Poor misunderstood 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"
答案 2 :(得分:2)
一个正确的例子可以创造奇迹:
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
(意味着如果您多次调用var
在相同的代码块中,如果有一个,它不会覆盖现有值。更重要的是,function
和console.log('foo' in window);
var foo;
console.log('foo' in window);
语句实际上被提升到其范围的顶部,这意味着:
true
将打印false
两次而不是true
,然后是{{1}}。
答案 3 :(得分:0)
方式1:
if (null === var)
(对旧浏览器):
if (void 0 != var)
另一个:
if(var)
并使用它像:
var un;
if (un==undefined)
{
alert('Yes');
} else {
alert('No');
}