[英]Javascript undefined, truthy vs typeof operator
Considering the following code: 考虑以下代码:
//the var Test has NOT been declared yet
console.log((typeof Test)); // "undefined"
console.log(Test); //"Uncaught ReferenceError: Test is not defined"
Why does the second console.log statement throw a ReferenceError and the first displays undefined. 为什么第二个console.log语句抛出ReferenceError而第一个显示未定义。
Because test is undefined. 因为测试是不确定的。
In that first console.log
you're asking the system to tell you the type of a variable. 在第一个
console.log
您要求系统告诉您变量的类型。 So it looks through the current scope chain to find a reference to that variable so it may infer its type. 因此,它会在当前作用域链中进行查找以找到对该变量的引用,以便可以推断出其类型。
When it doesn't find the variable, it receives the undefined
primitive. 当找不到变量时,它将接收
undefined
原语。 Which has a type, as I'm sure you've guessed, of undefined
. 我确信您已经猜到了,它的类型为
undefined
。
The second time you're asking it to print out the value of an undefined variable. 第二次要求您打印出未定义变量的值。 Since the variable is not defined (there is no reference to it in the current scope chain), this is an error you're trying to ACCESS DATA that doesn't exist, not just infer its type.
由于未定义变量(当前作用域链中没有对该变量的引用),因此您尝试访问不存在的ACCESS DATA不仅是推断其类型,这是一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.