为什么 null 是一个对象,null 和 undefined 有什么区别?
为什么 JavaScript 中 null
被视为 object
?
检查
if ( object == null )
Do something
与 一样吗
if ( !object )
Do something
?
另外:
null
和 undefined
之间有什么区别?
Why is null
considered an object
in JavaScript?
Is checking
if ( object == null )
Do something
the same as
if ( !object )
Do something
?
And also:
What is the difference between null
and undefined
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(25)
什么是类型?
类型是对值进行分类的一种方式。。 这是一个表格,其中包含相关类型及其
typeof
结果。typeof
结果typeof
结果是谎言吗?undefined
"undefined"
null
"object"
{}
,{a: "b"}
, ..."object"
null
是 不是一个对象,它的值类型为 Null。typeof
运算符在说谎! 它为null
返回"object"
是 JavaScript 语言中的一个错误。我在我的开源电子书中写了一个关于此的章节。 您可以在这里阅读https://github.com/carltheperson/advanced-js-objects
What is a type?
A type is a way to categorize values. Here is a table with the types in question and their
typeof
result.typeof
resulttypeof
result a lie?undefined
"undefined"
null
"object"
{}
,{a: "b"}
, ..."object"
null
is not an object, its a value of type Null.The
typeof
operator is lying! It returning"object"
fornull
is a mistake in the JavaScript language.I wrote a chapter about this in my open-source e-book. You can read it here https://github.com/carltheperson/advanced-js-objects
看这个:
Look at this:
null
是一个对象。 它的类型为空。undefined
不是一个对象; 它的类型是未定义的。null
is an object. Its type is null.undefined
is not an object; its type is undefined.与 undefined 相比,null 的另一个有趣之处在于它可以递增。
这对于设置计数器的默认数值很有用。 您在变量声明中将变量设置为 -1 有多少次?
The other fun thing about null, compared to undefined, is that it can be incremented.
This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?
2.Undefine 本身是类型,而 Null 是对象。
3.Javascript本身可以将任何未分配的变量初始化为未定义,但它永远不能将变量的值设置为null。 这必须以编程方式完成。
2.Undefined is a type itself while Null is an object.
3.Javascript can itself initialize any unassigned variable to undefined but it can never set value of a variable to null. This has to be done programatically.
使用 null 将某些内容定义为没有值,当您期望某些内容可能根本没有定义时,使用 undefined 。
例如,如果变量没有值,则将其指定为 null。
如果您预计某些内容可能根本未定义,例如可选选项参数,请使用 undefined。
Use null to define something as having no value, use undefined when you expect something might not be defined at all.
For example, if a variable has no value, assign it as null.
If you expect that something might be not defined at all, e.g. an optional options argument, use undefined.
未定义和未定义并不是同一件事。
您:
年龄
的值是多少?计算机:好的,让我检查我的内存/参考表......此时(您询问的时间),我没有看到任何名为
age
的标识符,不在这个范围/上下文中或任何父范围/上下文; 我不知道年龄
。 也许稍后我会遇到一条将该标识符添加到内存中的指令,但它现在不存在。你:
age
的值是多少;计算机:好的,检查我的内存...我在参考表中看到一个名为
age
的标识符,但在我添加它时没有值或指针或任何内容分配给它,所以我不知道不知道; 你可以认为它(age
)是空的/什么都没有/无用的。你:
age
的值是多少;计算机:好的,检查我的记忆...我在参考表中看到
age
:它为空。 基本上,它什么都没有/空,你不能用这个值做任何事情; 这是故意的。现在,我可能不应该这样解释,但希望它能有意义。
我明白为什么 null 被设计为 JS 中的对象,我个人喜欢这样。
null
和undefined
practically 表示同一件事:空/什么都没有。 区别在于它在概念上的使用方式。我将
null
视为开发人员意图的虚无; 某些东西为空是故意做的,不代表任何东西。 我将未定义视为计算机意图的虚无; 开发者/用户意外地没有价值的东西。例如,如果您从库/sdk 调用函数并返回 null,则几乎可以确定这是开发人员/作者故意设计的; 他们特别想表明虚无。
另请参阅 - https://developer.mozilla.org /en-US/docs/Web/JavaScript/Reference/Operators/null
Not defined and undefined are not the same thing happening.
You: What is the value of
age
?Computer: Okay, let me check my memory/reference table..... at this point (the time of you asking), i do not see any identifier named
age
, not in this scope/context or any parent scope/context;age
is not known to me. Maybe later i will come across an instruction to add that identifier to memory, but it does not exist right now.You: What is the value of
age
;Computer: Okay, checking my memory... I see an identifier in my reference table with that name
age
but no value or pointer or anything was assigned to it at the time i added it, so i don't know; you can consider it (age
) empty/nothing/useless.You: What is the value of
age
;Computer: Okay, checking my memory... i see
age
in my reference table: it is null. Basically, it is nothing/empty, you cannot do anything with this value; this was intentional.Now, i probably should not explain it this way but hopefully it will make sense.
I can see why null was designed to be an object in JS, and i personally like it that way.
null
andundefined
practically means the same thing: empty/nothing. The difference is in how it is used conceptually.I look at
null
as developer-intended nothingness; something being null was done on purpose to represent nothing. I look at undefined as computer-intended nothingness; something not having value by accident of the developer/user.For example, if you call a function from a library/sdk and got back null, you can almost be sure that was designed on purpose by the developer/author; they specifically wanted to indicate nothingness.
Also see - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null
null 和 undefined 的主要区别在于 null 代表
丢失的对象,而 undefined 表示变量的未初始化状态。
您可以将 null 视为未定义的对象,但 undefined 只会是未定义的
因为它的类型是未定义的。
The main difference between null and undefined is that null represents
a missing object, while undefined represents an uninitialized state of a variable.
You can think of null as an undefined object but undefined will be undefined only
since its type is undefined.
您:
名字
是什么? (*)JavaScript:
名称
?名称
是什么? 我不知道你在说什么。 您之前从未提及过任何名字
。 您是否在(客户端)看到其他脚本语言?你:
名字
是什么?JavaScript:我不知道。
简而言之;
未定义
是指不存在该事物的概念; 它没有类型,并且之前从未在该范围内被引用过;null
是已知该事物存在的位置,但不知道该事物的值是什么。要记住的一件事是,从概念上讲,
null
与false
或""
等不同,即使它们在类型转换后相等,即您:
名字
是什么?JavaScript: 布尔值 false。
你:
名字
是什么?JavaScript: 空字符串
*:
name
在此上下文中表示从未定义过的变量。 它可以是任何未定义的变量,但是,名称几乎是任何 HTML 表单元素的属性。 它的历史可以追溯到很久以前,并且早在 id 之前就已经制定了。 它很有用,因为 id 必须是唯一的,但名称不必如此。You: What is
name
? (*)JavaScript:
name
? What's aname
? I don't know what you're talking about. You haven't ever mentioned anyname
before. Are you seeing some other scripting language on the (client-)side?You: What is
name
?JavaScript: I don't know.
In short;
undefined
is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope;null
is where the thing is known to exist, but it's not known what the value is.One thing to remember is that
null
is not, conceptually, the same asfalse
or""
or such, even if they equate after type casting, i.e.You: What is
name
?JavaScript: Boolean false.
You: What is
name
?JavaScript: Empty string
*:
name
in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.差异可以总结为以下代码片段:
检查
object == null
与检查if (!object )
不同。后者等于
! Boolean(object)
,因为一元!
运算符会自动将右侧操作数转换为布尔值。由于
Boolean(null)
等于 false,因此!false === true
。因此,如果您的对象not null、butfalse或0或"" ,检查将通过
因为:
The difference can be summarized into this snippet:
Checking
object == null
is different to checkif ( !object )
.The latter is equal to
! Boolean(object)
, because the unary!
operator automatically cast the right operand into a Boolean.Since
Boolean(null)
equals false then!false === true
.So if your object is not null, but false or 0 or "", the check will pass
because:
null
是不是一个对象,它是一个原始值。 例如,您不能向其添加属性。 有时人们错误地认为它是一个对象,因为typeof null
返回“object”
。 但这实际上是一个错误(甚至可能在 ECMAScript 6 中修复)。null
和undefined
之间的区别如下:undefined
:由 JavaScript 使用,表示“无值”。 未初始化的变量、缺失的参数和未知的变量都具有该值。<前><代码>> var noValueYet;
> console.log(noValueYet);
不明确的
> 函数 foo(x) { console.log(x) }
> foo()
不明确的
> var obj = {};
> console.log(obj.unknownProperty)
不明确的
但是,访问未知变量会产生异常:
<前><代码>> 未知变量
ReferenceError:未知变量未定义
null
:程序员使用它来指示“无值”,例如作为函数的参数。检查变量:
作为一般规则,在 JavaScript 中应始终使用 === 而决不使用 ==(== 执行 各种可能产生意外结果的转换)。 检查
x == null
是一种边缘情况,因为它适用于null
和undefined
:检查变量是否已定义的常见方法a value就是将其转换为boolean,看是否为
true
。 该转换由if
语句和布尔运算符 ! (“不是”)。这种方法的缺点:以下所有值都计算为
false
,因此您必须小心(例如,上述检查无法区分undefined
和0
)。未定义
、null
false
+0
、-0
、< code>NaN""
您可以通过使用
Boolean
作为函数来测试布尔值的转换(通常它是一个构造函数,与 <代码>新):null
is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, becausetypeof null
returns"object"
. But that is actually a bug (that might even be fixed in ECMAScript 6).The difference between
null
andundefined
is as follows:undefined
: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.Accessing unknown variables, however, produces an exception:
null
: used by programmers to indicate “no value”, e.g. as a parameter to a function.Examining a variable:
As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check
x == null
is an edge case, because it works for bothnull
andundefined
:A common way of checking whether a variable has a value is to convert it to boolean and see whether it is
true
. That conversion is performed by theif
statement and the boolean operator ! (“not”).Drawback of this approach: All of the following values evaluate to
false
, so you have to be careful (e.g., the above checks can’t distinguish betweenundefined
and0
).undefined
,null
false
+0
,-0
,NaN
""
You can test the conversion to boolean by using
Boolean
as a function (normally it is a constructor, to be used withnew
):没有定义的属性是
未定义
。null
是一个对象。 它的类型是对象
。 null 是一个特殊值,意思是“没有值。undefined 不是一个对象,它的类型是未定义的。您可以声明一个变量,将其设置为 null,行为是相同的,只是您会看到打印出“null”与“您甚至可以将未定义的变量与 null 进行比较,反之亦然,条件将为 true:
请参阅 JavaScript null 和 undefined 之间的差异了解更多详细信息。
并使用新的编辑 yes
当测试 if
object
为 false 时,它们都只满足测试 if false 时的条件,而当测试 true 时则不满足这里检查:Javascript 陷阱
A property when it has no definition is
undefined
. anull
is an object. Its type isobject
. null is a special value meaning "no value. undefined is not an object, its type is undefined.You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
Refer to JavaScript Difference between null and undefined for more detail.
and with your new edit yes
when testing if
object
is false, they both only meet the condition when testing if false, but not when trueCheck here: Javascript gotcha
问题的第一部分:
这是一个 JavaScript 设计错误,他们现在无法修复。 它应该是 null 类型,而不是 object 类型,或者根本没有。 在检测真实对象时需要进行额外的检查(有时会被遗忘),并且是错误的根源。
问题的第二部分:
这两个检查始终都是 false,除了:
对象未定义或 null:均为 true。
对象是原始的,并且 0、
""
或 false:首先检查 false,第二个检查 true。如果对象不是基元,而是真实对象,例如
new Number(0)
、new String("")
或new Boolean(false)
,那么两个检查都是假的。因此,如果“对象”被解释为真正的对象,那么两个检查总是相同的。 如果允许原语,则对 0、
""
和 false 的检查会有所不同。在诸如
object==null
的情况下,不明显的结果可能是错误的根源。 不建议使用==
,而是使用===
。问题的第三部分:
在 JavaScript 中,一个区别是 null 是 object 类型,而 undefined 是 undefined 类型。
在 JavaScript 中,
null==undefined
为 true,如果类型被忽略,则被视为相等。 为什么他们这么决定,但 0、""
和 false 不相等,我不知道。 这似乎是一种武断的意见。在 JavaScript 中,
null===undefined
不为 true,因为===
中的类型必须相同。实际上,null 和 undefined 是相同的,因为它们都代表不存在。 0 和
""
也是如此,也许还有空容器[]
和{}
。 如此多类型的相同内容会导致错误。 一种或根本没有更好。 我会尝试尽可能少地使用。“假”、“真”和“!” 是另一堆可以简化的蠕虫,例如,单独使用
if(!x)
和if(x)
就足够了,不需要 true 和 false。如果没有给出值,则声明的 var x 是未定义类型,但它应该与 x 从未声明过一样。 另一个错误来源是一个空的空容器。 所以最好是一起声明和定义,如
var x=1
。人们兜圈子,试图弄清楚所有这些不同类型的虚无,但它们只是穿着复杂的不同衣服的同一件事。 现实是
也许所有人都应该抛出异常。
First part of the question:
It is a JavaScript design error they can't fix now. It should have been type null, not type object, or not have it at all. It necessitates an extra check (sometimes forgotten) when detecting real objects and is source of bugs.
Second part of the question:
The two checks are always both false except for:
object is undefined or null: both true.
object is primitive, and 0,
""
, or false: first check false, second true.If the object is not a primitive, but a real Object, like
new Number(0)
,new String("")
, ornew Boolean(false)
, then both checks are false.So if 'object' is interpreted to mean a real Object then both checks are always the same. If primitives are allowed then the checks are different for 0,
""
, and false.In cases like
object==null
, the unobvious results could be a source of bugs. Use of==
is not recommended ever, use===
instead.Third part of the question:
In JavaScript, one difference is that null is of type object and undefined is of type undefined.
In JavaScript,
null==undefined
is true, and considered equal if type is ignored. Why they decided that, but 0,""
and false aren't equal, I don't know. It seems to be an arbitrary opinion.In JavaScript,
null===undefined
is not true since the type must be the same in===
.In reality, null and undefined are identical, since they both represent non-existence. So do 0, and
""
for that matter too, and maybe the empty containers[]
and{}
. So many types of the same nothing are a recipe for bugs. One type or none at all is better. I would try to use as few as possible.'false', 'true', and '!' are another bag of worms that could be simplified, for example,
if(!x)
andif(x)
alone are sufficient, you don't need true and false.A declared
var x
is type undefined if no value is given, but it should be the same as if x was never declared at all. Another bug source is an empty nothing container. So it is best to declare and define it together, likevar x=1
.People are going round and round in circles trying to figure out all these various types of nothing, but it's all just the same thing in complicated different clothes. The reality is
And maybe all should throw exceptions.
TLDR
undefined
是 JavaScript 中的一个原始值,表示隐式缺少某个值。 未初始化的变量自动具有此值,并且没有显式return
语句的函数将返回undefined
。null
也是 JavaScript 中的原始值。 它表示故意缺少对象值。 JavaScript 中的null
旨在实现与 Java 的互操作性。typeof null
返回"object"
,因为该语言的设计具有特殊性,源于 JavaScript 与 Java 互操作的要求。 这并不意味着null
是对象的实例。 这意味着:给定 JavaScript 中的原始类型树,null
是“对象类型原始”子树的一部分。 下面对此进行更全面的解释。详细信息
undefined
是一个原始值,表示 隐式缺少值。 请注意,直到 1998 年的 JavaScript 1.3。这告诉我们null
旨在成为程序员在明确指示不存在值时使用的值。 未初始化的变量自动具有值undefined
。undefined
是一个one-of-a- ECMAScript 规范中的 kind 类型。null
是一个原始值,表示有意缺少一个对象值。null
也是一个 one-of-a ECMAScript 规范中的-kind 类型。JavaScript 中的
null
旨在实现与 Java 的互操作性,无论是从“外观”角度还是从编程角度(例如计划于 1996 年推出的 LiveConnect Java/JS 桥) )。 此后,布伦丹·艾奇 (Brendan Eich) 和其他人都对包含两个“缺乏价值”的价值观表示厌恶,但在 1995 年,艾奇奉命“让 [JavaScript] 看起来像 Java”。布伦丹·艾奇:
为了适应 Java 的
null
概念,由于 Java 的强类型特性,它只能分配给类型为引用类型(而不是基元)的变量,Eich 选择将特殊的 < code>null 值位于对象原型链的顶部(即引用类型的顶部),并将null
类型包含为“对象类型原语”集合的一部分”。此后不久添加了
typeof
运算符 在 JavaScript 1.1 中,于 1996 年 8 月 19 日发布。来自 V8 博客:
因此,Eich 设计了基本类型的层次结构,以实现与 Java 的互操作性。 这导致他将
null
与“对象类型原语”一起定位在层次结构上。 为了反映这一点,当typeof
添加到该语言后不久,他选择typeof null
返回“object”
。JavaScript 开发人员在
typeof null === "object"
中表达的惊讶是同时具有null 的弱类型语言 (JavaScript) 之间阻抗不匹配(或抽象泄漏)的结果
和undefined
,以及另一种只有null
的强类型语言 (Java),其中null
是 严格定义来引用引用类型(不是原始类型)。请注意,这都是合乎逻辑、合理且站得住脚的。
typeof null === "object"
不是一个 bug,而是必须适应 Java 互操作性的二阶效应。出现了许多不完美的向后合理化和/或约定,包括
未定义
表示隐式缺少值,null
表示有意缺少值; 或者,undefined
是指不存在值,而null
则是指不存在对象值。与 Brendan Eich 的相关对话,截图供后代使用:
TLDR
undefined
is a primitive value in JavaScript that indicates the implicit absence of a value. Uninitialized variables automatically have this value, and functions without an explicitreturn
statement, returnundefined
.null
is also a primitive value in JavaScript. It indicates the intentional absence of an object value.null
in JavaScript was designed to enable interoperability with Java.typeof null
returns"object"
because of a peculiarity in the design of the language, stemming from the demand that JavaScript be interoperable with Java. It does not meannull
is an instance of an object. It means: given the tree of primitive types in JavaScript,null
is part of the "object-type primitive" subtree. This is explained more fully below.Details
undefined
is a primitive value that represents the implicit absence of a value. Note thatundefined
was not directly accessible until JavaScript 1.3 in 1998. This tells us thatnull
was intended to be the value used by programmers when explicitly indicating the absence of a value. Uninitialized variables automatically have the valueundefined
.undefined
is a one-of-a-kind type in the ECMAScript specification.null
is a primitive value that represents the intentional absence of an object value.null
is also a one-of-a-kind type in the ECMAScript specification.null
in JavaScript was designed with a view to enable interoperability with Java, both from a "look" perspective, and from a programmatic perspective (eg the LiveConnect Java/JS bridge planned for 1996). Both Brendan Eich and others have since expressed distaste at the inclusion of two "absence of value" values, but in 1995 Eich was under orders to "make [JavaScript] look like Java".Brendan Eich:
In order to accommodate Java's concept of
null
which, due to the strongly-typed nature of Java, can only be assigned to variables typed to a reference type (rather primitives), Eich chose to position the specialnull
value at the top of the object prototype chain (i.e. the top of the reference types), and to include thenull
type as part of the set of "object-type primitives".The
typeof
operator was added shortly thereafter in JavaScript 1.1, released on 19th August 1996.From the V8 blog:
So Eich designed the hierarchy of primitive types to enable interoperability with Java. This led to him positioning
null
along with the "object-type primitives" on the hierarchy. To reflect this, whentypeof
was added to the language shortly thereafter, he chosetypeof null
to return"object"
.The surprise expressed by JavaScript developers at
typeof null === "object"
is the result of an impedance mismatch (or abstraction leak) between a weakly-typed language (JavaScript) that has bothnull
andundefined
, and another, strongly-typed language (Java) that only hasnull
, and in whichnull
is strictly defined to refer to a reference type (not a primitive type).Note that this is all logical, reasonable and defensible.
typeof null === "object"
is not a bug, but a second-order effect of having to accommodate Java interoperability.A number of imperfect backwards rationalisations and/or conventions have emerged, including that
undefined
indicates implicit absence of a value, and thatnull
indicates intentional absence of a value; or thatundefined
is the absence of a value, andnull
is specifically the absence of an object value.A relevant conversation with Brendan Eich, screenshotted for posterity:
值 null 表示有意不存在任何对象值。 它是 JavaScript 的原始值之一,对于布尔运算被视为 false。
x 被声明 & 定义为 null
y 已声明但未定义。 它被声明为没有值,因此它是未定义的。
z 未声明,因此如果您尝试使用 z 也将是未定义的。
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.
x is declared & defined as null
y is declared but not defined. It is declared with no value so it is undefined.
z is not declared so would also be undefined if you attempted to use z.
理解 null 和 undefined 的一种方法是了解它们出现的位置。
在以下情况下期望返回 null 值:
查询 DOM 的方法
从 Ajax 请求接收的 JSON 响应
RegEx.exec。
处于不断变化状态的新功能。 以下返回 null:
所有其他不存在的情况均由 undefined 表示(如@Axel 所示)。 以下每个打印“未定义”:
当然,如果您决定编写 var unialized = null; 或者自己从方法中返回 null,那么在其他情况下就会出现 null。 但这应该是很明显的。
第三种情况是当您想要访问一个变量但您甚至不知道它是否已被声明时。 对于这种情况,请使用 typeof 来避免引用错误:
总之,当您操作 DOM、处理 Ajax 或使用某些 ECMAScript 5 功能时,请检查 null。 对于所有其他情况,可以安全地检查未定义的严格相等性:
One way to make sense of null and undefined is to understand where each occurs.
Expect a null return value in the following situations:
Methods that query the DOM
JSON responses received from an Ajax request
RegEx.exec.
New functionality that is in a state of flux. The following returns null:
All other cases of non-existence are denoted by undefined (as noted by @Axel). Each of the following prints "undefined":
Of course if you decide to write var unitialised = null; or return null from a method yourself then you have null occurring in other situations. But that should be pretty obvious.
A third case is when you want to access a variable but you don't even know if it has been declared. For that case use typeof to avoid a reference error:
In summary check for null when you are manipulating the DOM, dealing with Ajax, or using certain ECMAScript 5 features. For all other cases it is safe to check for undefined with strict equality:
JavaScript 中许多不同空检查的比较:
http://jsfiddle.net/aaronhoffman/DdRHB/5/< /a>
http://aaron-hoffman. blogspot.com/2013/04/javascript-null-checking-undefined-and.html
Comparison of many different null checks in JavaScript:
http://jsfiddle.net/aaronhoffman/DdRHB/5/
http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html
添加到
undefined
和null
之间的区别是什么 的答案,来自 JavaScript 权威指南第 6 版,本页第 41 页:To add to the answer of What is the differrence between
undefined
andnull
, from JavaScript Definitive Guide 6th Edition, p.41 on this page:一些精度:
null 和未定义是两个不同的值。 一种表示名称不存在值,另一种表示名称不存在。
对于
if( o )
,if
中发生的情况如下:计算括号 o 中的表达式,然后开始执行
if
对括号中表达式的值进行类型强制 - 在我们的例子中为o
。JavaScript 中的 Falsy(将被强制为 false)值为:''、null、undefined、0 和 false。
Some precisions:
null and undefined are two different values. One is representing the absence of a value for a name and the other is representing the absence of a name.
What happens in an
if
goes as follows forif( o )
:The expression in the parentheses o is evaluated, and then the
if
kicks in type-coercing the value of the expression in the parentheses - in our caseo
.Falsy (that will get coerced to false) values in JavaScript are: '', null, undefined, 0, and false.
对于值相等(null==undefined),null 和 undefined 都是 false:它们都折叠为布尔值 false。 它们不是同一个对象(null!==未定义)。
undefined 是全局对象(浏览器中的“窗口”)的属性,但它是原始类型而不是对象本身。 它是未初始化的变量和没有 return 语句结尾的函数的默认值。
null 是对象的一个实例。 null 用于返回集合对象的 DOM 方法来指示空结果,这提供了 false 值而不指示错误。
null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).
undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.
null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.
以下函数显示了原因并能够计算出差异:
如果您调用,
您会得到
第一个
console.log(...)
尝试从myObj
获取myProperty
,而它尚未定义 - 所以它会返回“不明确的”。 将 null 分配给它后,第二个console.log(...)
显然返回“null”,因为myProperty
存在,但它的值为null
code> 分配给它。为了能够查询这种差异,JavaScript 有
null
和undefined
:虽然null
是 - 就像其他语言中的对象一样,< code>undefined 不能是对象,因为没有可用的实例(甚至不是null
实例)。The following function shows why and is capable for working out the difference:
If you call
You're getting
The first
console.log(...)
tries to getmyProperty
frommyObj
while it is not yet defined - so it gets back "undefined". After assigning null to it, the secondconsole.log(...)
returns obviously "null" becausemyProperty
exists, but it has the valuenull
assigned to it.In order to be able to query this difference, JavaScript has
null
andundefined
: Whilenull
is - just like in other languages an object,undefined
cannot be an object because there is no instance (even not anull
instance) available.例如,
window.someWeirdProperty
未定义,因此"window.someWeirdProperty === null"
计算结果为 false,而"window.someWeirdProperty === undefined"
code> 计算结果为 true。此外,检查
if (!o)
与检查if (o == null)
是否o
为false
不同代码>.For example
window.someWeirdProperty
is undefined, so"window.someWeirdProperty === null"
evaluates to false while"window.someWeirdProperty === undefined"
evaluates to true.Moreover checkif
if (!o)
is not the same as checkingif (o == null)
foro
beingfalse
.摘自 Nicholas C. Zakas 的《面向对象 Javascript 原理》
Zakas,尼古拉斯·C. (2014-02-07)。 面向对象 JavaScript 的原理(Kindle 位置 226-227)。 无淀粉压榨机。 Kindle版。
也就是说:
未定义的情况:
From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas
Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.
That said:
Undefined case:
思考“null”的最佳方法是回忆一下类似概念在数据库中的使用方式,它表示某个字段“根本不包含任何值”。
对于编写更容易调试的程序来说,这是一种非常有用的技术。 一个“未定义”的变量可能是错误的结果......(你怎么知道?)......但是如果该变量包含值“null”,你就知道“某人,某处在这个程序中,将其设置为“null”。”因此,我建议,当您需要删除变量的值时,不要“删除”...将其设置为'无效的。' 旧值将被孤立,很快就会被垃圾收集; 新值是“(现在)没有价值”。 在这两种情况下,变量的状态都是确定的:“显然,它是故意的。”
The best way to think about 'null' is to recall how the similar concept is used in databases, where it indicates that a field contains "no value at all."
This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."
在 Javascript 中,
null
不是object
类型,它是primitave
类型。有什么区别?
未定义指的是尚未设置的指针。
Null 指的是空指针,例如有人手动将变量设置为
null
类型In Javascript
null
is not anobject
type it is aprimitave
type.What is the difference?
Undefined refers to a pointer that has not been set.
Null refers to the null pointer for example something has manually set a variable to be of type
null