"定义"之间有什么区别?并在javascript中定义?

时间:2015-01-29 22:08:54

标签: javascript

在javascript中编写时,我看到它以两种不同的方式编写:

if (typeof x === "undefined") {
// execute code here
}

if (typeof x === undefined) {
// execute code here
}

我的问题是:

"undefined"undefined之间有什么区别?一个用引号括起来,另一个不用。

有人可以为我澄清这个吗?

谢谢!

2 个答案:

答案 0 :(得分:8)

undefined是一个值,'undefined'是一个字符串文字。 typeof运算符返回一个字符串,为您提供类型。因此typeof x返回x类型的字符串名称。

使用if( x === undefined )if( typeof x === 'undefined' )但不使用if( typeof x === undefined ),因为typeof x将始终返回一个字符串(永远不会等于undefined)。

答案 1 :(得分:0)

"undefined"是一个字符串,undefined是一个包含原始 undefined的变量(谢谢elclanrs)。

如果if(typeof x === undefined)被重新分配给匹配x类型的字符串,

undefined应该只能返回true。