简体   繁体   English

Javascript未定义,真实vs typeof运算符

[英]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.

相关问题 //(typeof(myVar)?= “undefined”)// 逻辑上等价于真值 //if (myVar) 吗? - Is //(typeof(myVar) != “undefined”)// logically equivalent to the truthy //if (myVar)? JavaScript typeof运算符编号与字符串 - JavaScript typeof Operator-Number vs String typeof a =='undefined'vs typeof a ==='undefined' - typeof a == 'undefined' vs typeof a === 'undefined' JavaScript未定义变量检测:typeof ===“undefined”vs双重感叹号 - JavaScript undefined variable detection: typeof===“undefined” vs double exclamation JavaScript:typeof(var)==='undefined' 与 =='undefined' 之间的区别? - JavaScript: difference between typeof(var)==='undefined' vs =='undefined'? 了解 Javascript 中的 typeof 运算符 - Understanding the typeof operator in Javascript 通过使用javascript Truthy和Falsy Value VS'==='运算符来检查语句是对还是错 - Check If statement is true or false by using javascript Truthy and Falsy Value VS '===' operator 为什么在使用比较运算符与使用!!时将整数转换为真实值的工作方式不同! 在JavaScript中 - Why converting an integer to truthy value works differently when using comparison operator vs using !! in JavaScript Javascript中“if typeof undefined”的简写? - Shorthand for “if typeof undefined” in Javascript? eval typeof在javascript中未定义 - eval typeof is undefined in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM