简体   繁体   English

Javascript未定义对象

[英]Javascript undefined object

I know the best way to check if a variable is undefined is 我知道检查变量是否未定义的最好方法是

if ( typeof( something ) == "undefined") 

What I don't understand is when is a variable undefined and when is an object undefined. 我不明白的是,何时未定义变量,何时未定义对象。 For instance when I console.log() the a variable I get 例如当我console.log()一个变量我得到

Object {detailedView: undefined}

My question is why I am getting this and not a plain undefined. 我的问题是为什么我得到这个,而不是一个普通的未定义。

a isn't undefined. a不是不确定的。 It's defined. 已定义。 It's an object. 这是一个对象。 That object just so happens to contain a property that is undefined , but the variable itself isn't undefined. 该对象恰好包含undefined的属性,但变量本身并非未定义。

something isn't defined, so it's undefined . something没有定义,所以是undefined

There are two things here: the "value" undefined , which is a value that a variable can point to when it has been declared but not assigned anything yet (ie var a; ), or when it's been assigned something that doesn't actually have a value or exists, and there is the string "undefined" , which is a string similar to "monkey" or "collywobble". 这里有两件事: undefined的“值”,它是变量在已声明但尚未分配任何东西时可以指向的值(即var a; ),或在分配了实际上没有分配的东西时指向的值具有值或存在,并且存在字符串"undefined" ,它是类似于“ monkey”或“ collywobble”的字符串。

In your conditional, you're testing to see what the result of the typeof operator is, which is a string "object" or "function", or in this case "undefined". 在您的条件中,您正在测试以查看typeof运算符的结果是什么,它是字符串“ object”或“ function”,或者在这种情况下为“ undefined”。 Those are just words: 这些只是单词:

if(typeof a == "undefined")

is the same as testing 与测试相同

if(a == undefined)

So, when you console.log the actual object, you'll see it has a value undefined , rather than being a string "undefined" . 因此,当您console.log实际对象时,您会看到它的值是undefined ,而不是字符串"undefined"

I believe you're asking about the difference between "undefined variables" (variables never declared) and "undefined values" (the value undefined inside a variable or property). 我相信你问“未定义的变量”(变量从未宣布过)和“未定义值”(价值之间的差额undefined变量或属性里面)。

You define/declare a variable with the var keyword: 您可以使用var关键字定义/声明变量:

var myVariable;

If you just do that, the value of that variable is undefined : 如果您只是这样做,则该变量的值是undefined

console.log(myVariable); // undefined

If you don't declare a variable, you cannot use it: 如果声明变量,则不能使用它:

console.log(myOtherVariable); // throws a ReferenceError

... except in typeof : ...除了typeof

typeof myOtherVariable == "undefined"; // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM