Javascript undefined,truthy vs typeof运算符

时间:2014-03-10 01:13:17

标签: javascript typeof referenceerror

考虑以下代码:

//the var Test has NOT been declared yet

console.log((typeof Test)); // "undefined"
console.log(Test); //"Uncaught ReferenceError: Test is not defined"

为什么第二个console.log语句抛出一个ReferenceError,第一个显示undefined。

1 个答案:

答案 0 :(得分:5)

因为测试未定义。

在第一个console.log中,您要求系统告诉您变量的类型。因此,它通过当前作用域链查找该变量的引用,以便它可以推断出它的类型。

当它找不到变量时,它会收到undefined原语。正如我相信你已经猜到的那样,undefined

第二次要求它打印出未定义变量的值。由于未定义变量(当前作用域链中没有对它的引用),这是您尝试访问不存在的数据的错误,而不仅仅是推断它的类型。