3

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

typeof foo将返回两个“未定义”,foo in window并将返回两个 true;

4

4 回答 4

10

var foo暗示var foo=undefined,除非当然undefined设置为undefined.

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

于 2012-06-12T15:08:27.487 回答
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

这是一个小提琴

此外,在任何函数上下文之外声明都会使用if值进行var foo实例化(这意味着如果您在同一个代码块中多次调用,它不会覆盖现有值(如果有的话))。更重要的是,and语句实际上被提升到其范围的顶部,这意味着:window.fooundefined!('foo' in window)var foovarfunction

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

将打印true两次而不是false后跟true.

于 2012-06-12T15:19:06.857 回答
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;

请注意,它们是在不同时间发生的完全不同的事情。声明和“初始化”(实际上是一个赋值)是分开发生的。声明发生在进入执行单元时;初始化/分配稍后发生,作为逐步代码执行的一部分。(更多:可怜的误解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"
于 2012-06-12T15:13:53.770 回答
0

方式一:

if (null === var)


(对于旧浏览器):

if (void 0 != var)


另一个:

if(var) 


并像这样使用它:

var un;
if (un==undefined)
{
alert('Yes');
} else {
alert('No');
}
于 2012-06-12T15:20:31.677 回答