JavaScript 中 null 和 undefined 有什么区别?
JavaScript 中 null
和 undefined
有什么区别?
What is the difference between null
and undefined
in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
undefined
表示变量已被声明但尚未赋值:null
是一个赋值值。它可以被分配给一个变量作为无值的表示:从前面的示例中可以清楚地看出,
undefined
和null
是两种不同的类型:undefined
本身就是一个类型(未定义),而null
是一个对象。证明 :
和
undefined
means a variable has been declared but has not yet been assigned a value :null
is an assignment value. It can be assigned to a variable as a representation of no value :From the preceding examples, it is clear that
undefined
andnull
are two distinct types:undefined
is a type itself (undefined) whilenull
is an object.Proof :
and
这种差异可以用卫生纸支架来解释:
非零值就像一个带有卫生纸卷的支架,并且管子上仍然有纸巾。
零值就像一个带有空卫生纸管的支架。
空值就像一个甚至没有纸巾管的支架。
未定义的值类似于持有人本身丢失。
< /a>
The difference can be explained with toilet tissue holder:
A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.
A zero value is like a holder with an empty toilet tissue tube.
A null value is like a holder that doesn't even have a tissue tube.
An undefined value is similar to the holder itself being missing.
我从这里选择了这个
当您通过 var 声明变量并且不给它赋值时,它将具有未定义的值。就其本身而言,如果您尝试 WScript.Echo() 或alert() 这个值,您将看不到任何内容。但是,如果您向其附加一个空白字符串,那么它会突然出现:
您可以声明一个变量,将其设置为 null,并且行为是相同的,只是您会看到打印出“null”与“undefined”。这确实是一个很小的差异。
您甚至可以将未定义的变量与 null 进行比较,反之亦然,条件将为 true:
但是,它们被视为两种不同的类型。虽然 undefined 本身就是一个类型,但 null 被认为是一个特殊的对象值。您可以通过使用 typeof() 来查看这一点,它返回一个表示变量一般类型的字符串:
运行上述脚本将产生以下输出:
无论它们的类型不同,如果您尝试访问它们,它们的行为仍然相同任一成员,例如,这就是说他们将抛出异常。使用 WSH,您将看到可怕的“'varname' 为 null 或不是对象”,如果您幸运的话(但这是另一篇文章的主题)。
您可以显式地将变量设置为未定义,但我强烈建议不要这样做。我建议仅将变量设置为 null,并将您忘记设置的值保留为未定义。同时,我真的鼓励您始终设置每个变量。 JavaScript 的作用域链与 C 风格语言不同,即使是资深程序员也很容易感到困惑,而将变量设置为 null 是防止基于它的错误的最佳方法。
您将看到未定义弹出的另一个实例是使用删除运算符时。我们这些来自 C 世界的人可能会错误地将其解释为破坏一个物体,但事实并非如此。此操作的作用是从数组中删除下标或从对象中删除成员。对于数组,它不会影响长度,但下标现在被认为是未定义的。
上面脚本的结果是:
当读取一个不存在的下标或成员时,你也会得到 undefined 返回。
null 和 undefined 之间的区别是:JavaScript 永远不会将任何内容设置为 null,这通常是我们所做的。虽然我们可以将变量设置为 undefined,但我们更喜欢 null,因为这不是为我们做过的事情。当您调试时,这意味着任何设置为 null 的内容都是您自己完成的,而不是 JavaScript。除此之外,这两个特殊值几乎相等。
I picked this from here
When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.
You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:
Running the above script will result in the following output:
Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).
You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.
Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.
The result of the above script is:
You will also get undefined returned when reading a subscript or member that never existed.
The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.
请仔细阅读以下内容。它应该消除您对 JavaScript 中
null
和undefined
之间差异的所有疑虑。此外,您可以使用本答案末尾的实用函数来获取更具体类型的变量。在 JavaScript 中,我们可以有以下类型的变量:
undefined
分配null
以外的任何内容分配的变量undefined
或null
下面一一解释这些情况:
未声明的变量
typeof
运算符进行检查== undefined
) 进行检查,更不用说严格相等运算符 (=== undefined
),以及 if 语句 和 三元运算符 (
? :
) - 这些会抛出引用错误已声明但未分配的变量< /strong>
typeof
返回字符串'undefined'==
检查null
返回true
==
检查undefined
返回true
===
检查null
返回false
===
检查undefined
返回true
? :
)用文字
undefined 赋值的变量
这些变量的处理方式与已声明但未分配的变量完全相同。
用文字指定的变量
null
typeof
返回字符串'object'==
检查null
返回true
==
检查undefined
返回true
===
检查null
返回true
===
检查undefined
返回false
? :
)分配除
undefined
或null
之外的变量
下面提供了对变量进行正确类型检查的算法:
typeof
,如果不是'则返回它object'null
,因为typeof null
返回 'object' 以及Object
的toString
方法返回类似于本机/主机对象的 '[object ConstructorName]' 的字符串。对于所有其他对象(用户定义的对象),它始终返回 '[object Object]'true
,它将尝试通过toString
获取构造函数的名称,并且从那里提取名称。如果无法访问构造函数,则照常返回'object'。如果字符串不包含其名称,则返回 'anonymous'(支持 ECMAScript 2020 之前的所有类型)
Please read the following carefully. It should remove all your doubts regarding the difference between
null
andundefined
in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.In JavaScript we can have the following types of variables:
undefined
null
undefined
ornull
The following explains each of these cases one by one:
Undeclared Variables
typeof
operator which returns string 'undefined'== undefined
), let alone the strict equality operator (=== undefined
),as well as if-statements and ternary operators (
? :
) — these throw Reference ErrorsDeclared but Unassigned Variables
typeof
returns string 'undefined'==
check withnull
returnstrue
==
check withundefined
returnstrue
===
check withnull
returnsfalse
===
check withundefined
returnstrue
? :
)Variables assigned with literal
undefined
These variables are treated exactly the same as Declared But Unassigned Variables.
Variables assigned with literal
null
typeof
returns string 'object'==
check withnull
returnstrue
==
check withundefined
returnstrue
===
check withnull
returnstrue
===
check withundefined
returnsfalse
? :
)Variables assigned with anything other than
undefined
ornull
Following provides the algorithm for correct type checking of a variable:
typeof
our variable and return it if it isn't 'object'null
, astypeof null
returns 'object' as wellObject
'stoString
method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'true
, it will try to get the name of the constructor bytoString
-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned(supports all types up to ECMAScript 2020)
null 是一个特殊关键字,表示缺少值。
将其视为一个值,例如:
undefined属性表示变量还没有被赋值,包括null。
就像
定义的空变量是数据类型
未定义
的null
一样,它们都表示没有值的变量的值
和
null
不代表没有值的字符串 - 空字符串 -Like
现在如果
BUT
SO 每个人都有自己的使用方式
undefined 使用它来比较变量数据类型
null 使用它来清空变量的值
null is a special keyword that indicates an absence of value.
think about it as a value, like:
undefined property indicates that a variable has not been assigned a value including null too .
Like
defined empty variable is
null
of datatypeundefined
Both of them are representing a value of a variable with no value
AND
null
doesn't represent a string that has no value - empty string-Like
Now if
BUT
SO each one has it own way to use
undefined use it to compare the variable data type
null use it to empty a value of a variable
null:变量没有值; 未定义:变量本身不存在;
..其中变量是与值关联的符号名称。
JS 可以很好地使用 null 隐式初始化新声明的变量,但事实并非如此。
null: absence of value for a variable; undefined: absence of variable itself;
..where variable is a symbolic name associated with a value.
JS could be kind enough to implicitly init newly declared variables with null, but it does not.
已经给出了很多“技术”答案,从 JS 作为一种编程语言的有限角度来看,它们大多都是正确的。
但是,我想添加以下想法,特别是当您将 TypeScript 代码作为更大的项目/(企业)应用程序的一部分编写时:
因此,为了协调事情,我严格反对使用“null”,并希望鼓励您停止在代码中使用“null”。这比您想象的要容易得多。别误会我的意思。我并不是说不处理“空”值,只是为了避免在代码中显式使用它们。换句话说:您的代码仍然应该能够处理来自应用程序外部的意外传递的“空”值,例如通过像 Angular,或第 3 方后端。
以下是使其成为可能的准则:
if (value === undefined) { ... }
。if (value) { ... }
if (!value && value !== 0) { ... }
)A lot of "technical" answers have been given, all of them mostly correct from the limited point of view of JS as a mere programming language.
However, I would like to add the following thoughts, especially when you're writing TypeScript code as part of a bigger project / (enterprise) application:
Therefore, in an effort to harmonize things I'm strictly against using "null" and want to encourage you to stop using "null" in your code. It's far easier than you might think. Don't get me wrong. I'm not talking about not handling "null" values, only to avoid explicitly using them in your code. Put differently: your code should still be able to work with accidentally passed "null" values coming from outside your application, e.g. via a 3rd party lib like Angular, or a 3rd party backend.
Here are the guidelines that make it possible:
if (value === undefined) { ... }
.if (value) { ... }
if (!value && value !== 0) { ... }
)通过 JavaScript:权威指南
via JavaScript:The Definitive Guide
理解差异的最好方法是首先理清 JavaScript 的内部工作原理,并理解它们之间的含义差异:
这三种情况之间存在含义差异,JavaScript 用两个不同的值来区分后两种情况、
null
和未定义
。您可以自由地明确使用这些值来传达这些含义。那么由于这种哲学基础而产生的一些 JavaScript 特定问题是什么?
没有初始值设定项的声明变量的值是
未定义
,因为您从未说过任何有关预期值的信息。从未设置过的对象属性的计算结果为
未定义
,因为没有人说过有关该属性的任何事情。null
和undefined
彼此“相似”,因为 Brendan Eich 是这么说的。但它们显然并不相等。null
和undefined
具有不同的类型。null
属于Null
类型,undefined
属于Undefine
类型。这是在规范中的,但你永远不会知道这一点,因为typeof
很奇怪,我不会在这里重复。在没有显式 return 语句的情况下到达其主体末尾的函数将返回
undefined
,因为您对它返回顺便说一句,JavaScript 中还有其他形式的“虚无”(学习哲学是件好事……)
NaN
ReferenceError< /code>
let
或const
定义的局部变量并接收ReferenceError
稀疏数组中的空单元格。是的,尽管它们将
===
与未定义进行比较,但它们甚至都不是未定义
。<前><代码>$节点
>常量 a = [1,未定义,2]
>常量 b = [1, , 2]
>一个
[ 1,未定义,2 ]
>乙
[ 1, <1 个空项目>, 2 ]
The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:
There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values,
null
andundefined
. You are free to use those values explicitly to convey those meanings.So what are some of the JavaScript-specific issues that arise due to this philosophical basis?
A declared variable without an initializer gets the value
undefined
because you never said anything about the what the intended value was.A property of an object that has never been set evaluates to
undefined
because no one ever said anything about that property.null
andundefined
are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.null
andundefined
thankfully have different types.null
belongs to the typeNull
andundefined
to the typeUndefined
. This is in the spec, but you would never know this because of thetypeof
weirdness which I will not repeat here.A function reaching the end of its body without an explicit return statement returns
undefined
since you don't know anything about what it returned.By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)
NaN
ReferenceError
let
orconst
defined local variable in its temporal dead zone and receiving aReferenceError
Empty cells in sparse arrays. Yes these are not even
undefined
although they compare===
to undefined.null
是一个特殊值,意思是“无值”。null
是一个特殊的对象,因为typeof null
返回“object”。另一方面,
undefined
表示该变量尚未声明,或者尚未赋值。null
is a special value meaning "no value".null
is a special object becausetypeof null
returns 'object'.On the other hand,
undefined
means that the variable has not been declared, or has not been given a value.null 和 undefined 是两种不同的对象类型,它们具有以下共同点:
==
和!=
运算符认为 null 和 undefined 值彼此相等,且不等于任何其他值。然而相似之处到此为止。这一次,关键字 null 和 undefined 的实现方式存在根本性差异。这并不明显,但请考虑以下示例:
undefined、NaN 和 Infinity 只是预初始化的“超全局”变量的名称 - 它们已初始化在运行时,可以被具有相同名称的普通全局或局部变量覆盖。
现在,让我们对 null 尝试同样的操作:
哎呀! null、true 和 false 是保留关键字 - 编译器不允许您将它们用作变量或属性名称
另一个区别是 undefined 是原始类型,而 null 是对象类型(表示不存在对象引用)。请考虑以下事项:
此外,在数字上下文中处理 null 和 undefined 的方式存在重要差异:
null 变为 0 当用于算术表达式或数字比较时 - 与 false 类似,它基本上只是一种特殊的“零”。另一方面,未定义是真正的“无”,当您尝试在数字上下文中使用它时,它会变成NaN(“不是数字”)。
请注意,null 和 undefined 会受到
==
和!=
运算符的特殊处理,但您可以测试 true a 和 b 与表达式(a >= b && a <= b)
的数值相等。null and undefined are two distinct object types which have the following in common:
==
and!=
operators.The similarities however end here. For once, there is a fundamental difference in the way how keywords null and undefined are implemented. This is not obvious, but consider the following example:
undefined, NaN and Infinity are just names of preinitialized "superglobal" variables - they are initialized at run-time and can be overridden by normal global or local variable with the same names.
Now, let's try the same thing with null:
Oops! null, true and false are reserved keywords - compiler won't let you use them as variable or property names
Another difference is that undefined is a primitive type, while null is an object type (indicating the absense of an object reference). Consider the following:
Also, there is an important difference in the way null and undefined are treated in numeric context:
null becomes 0 when used in arithmetic expressions or numeric comparisons - similarly to false, it is basically just a special kind of "zero". undefined, on the other hand, is a true "nothing" and becomes NaN ("not a number") when you try to use it in numeric context.
Note that null and undefined receive a special treatment from
==
and!=
operators, but you can test true numeric equality of a and b with the expression(a >= b && a <= b)
.我将解释
undefined
、null
和Uncaught ReferenceError
:1 -
Uncaught ReferenceError
:变量 has not已在您的脚本中声明,但没有引用此变量2 -
未定义
:已声明变量但未初始化3 -
null
:声明变量且为空值I'll explain
undefined
,null
andUncaught ReferenceError
:1 -
Uncaught ReferenceError
: variable has not been declared in your script, there is no reference to this varaible2 -
undefined
: Variable declared but does not initialised3 -
null
: Variable declared and is an empty value未定义意味着变量已被声明但没有值:
Null 是赋值:
Undefined means a variable has been declared but has no value:
Null is an assignment:
tl;dr
使用
null
设置一个您知道它是对象的变量。使用
undefined
设置混合类型的变量。这是我对 5 个原语和对象类型的用法,解释了
undefined
或null
的“用例”之间的区别。String
如果你知道一个变量在整个生命周期中只是一个字符串,按照惯例,你可以将它初始化为
""
:Number
如果你知道变量只是一个数字,而在整个生命周期中,按照惯例,您可以将其初始化为
0
(如果0
是一个重要的值,则为NaN
值):或
Boolean
如果您知道变量在整个生命周期中只是布尔值,按照惯例,您可以将其初始化为
false
:Object
如果您知道变量在整个生命周期中只是一个对象,按照惯例,您可以将其初始化为
null
:注意:null 的明智用法是 <对象的strong>falsy版本,因为对象始终为
true
,并且因为typeof null
返回object
。这意味着typeof myVarObject
为 Object 和 null 类型返回一致的值。全部
如果您知道变量具有混合类型(所有生命周期中的任何类型),按照惯例,您可以将其初始化为
undefined
。tl;dr
Use
null
for set a variable you know it is an Object.Use
undefined
for set a variable whose type is mixed.This is my usage of both 5 primitives and Object type, and that explain the difference between « use case » of
undefined
ornull
.String
If you know a variable is only a string while all lifecycle, by convention, you could initialize it, to
""
:Number
If you know a variable is only a number while all lifecycle, by convention, you could initialize it, to
0
(orNaN
if0
is an important value in your usage):or
Boolean
If you know a variable is only a boolean while all lifecycle, by convention, you could initialize it, to
false
:Object
If you know a variable is only an Object while all lifecycle, by convention, you could initialize it, to
null
:Note: the smart usage off null is to be the falsy version of an Object because an Object is always
true
, and becausetypeof null
returnobject
. That meanstypeof myVarObject
return consistent value for both Object and null type.All
If you know a variable has a mixed type (any type while all lifecycle), by convention, you could initialize it, to
undefined
.除了不同的含义之外,还有其他差异:
null
但省略undefined
In addition to a different meaning there are other differences:
null
but omitsundefined
JavaScript 中有 5 种基本数据类型:String、Number、Boolean、null 和 undefined。
我将尝试用一些简单的例子来解释。
假设我们有一个简单的函数
,此外,上面的函数 if(a == null) 与 if(!a) 相同。
现在,当我们在不传递参数 a 的情况下调用这个函数时
,
这也会给出 undefined;我们已经声明了一个变量,但我们还没有为该变量分配任何值;
但如果我们
这样写 null 就是一个对象。在某种程度上,我们为“a”分配了一个 null 值
In JavasScript there are 5 primitive data types: String, Number, Boolean, null and undefined.
I will try to explain with some simple examples.
Let's say we have a simple function
Also, in above
function if(a == null)
is the same asif(!a)
.Now when we call this function without passing the parameter a
also
This will give undefined; we have declared a variable but we have not asigned any value to this variable;
but if we write
so null is an object. In a way we have assigned a value null to 'a'
当您在 JavaScript 中声明变量时,它会被赋予值
undefined
。这意味着该变量未受影响,并且可以在将来分配任何值。它还意味着您不知道该变量在声明时将保存的值。现在您可以显式分配一个变量
null
。这意味着该变量没有任何值。例如 - 有些人没有中间名。因此,在这种情况下,最好将值 null 分配给 person 对象的 middlename 变量。现在假设有人正在访问您的 person 对象的 middlename 变量,并且它的值为
undefined
。他不知道开发人员是否忘记初始化该变量或者它是否没有任何值。如果它的值为null
,那么用户可以轻松推断 middlename 没有任何值,并且它不是一个未更改的变量。When you declare a variable in javascript, it is assigned the value
undefined
. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.Now you can explicitly assign a variable
null
. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.Now suppose that someone is accessing the middlename variable of your person object and it has the value
undefined
. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the valuenull
, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.好吧,当我们听到
null
和undefined
时,我们可能会感到困惑,但让我们从简单的开始,它们都是 falsy 并且在很多方面都很相似,但是 JavaScript 的奇怪部分,使它们有一些显着的差异,例如, typeofnull
是'object'
而 typeof未定义
是'未定义'
。但是,如果您使用
==
检查它们,如下所示,您会发现它们都是 falsy:此外,您还可以将
null
分配给对象属性或一个原语,而undefined
可以通过不分配任何东西来简单地实现。我创建了一个快速图像,让您一目了然地显示差异。
OK, we may get confused when we hear about
null
andundefined
, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeofnull
is'object'
while typeofundefined
is'undefined'
.But if you check them with
==
as below, you see they are both falsy:Also you can assign
null
to an object property or to a primitive, whileundefined
can simply be achieved by not assigning to anything.I create a quick image to show the differences for you at a glance.
对于
undefined
类型,只有一个值:undefined
。对于
null
类型,只有一个值:null
。因此对于它们两者来说,标签既是它的类型又是它的值。
它们之间的区别。例如:
null
是一个空值undefined
是一个缺失值或者:
undefined
还没有值null 曾经有一个值,但现在不再有值了。
实际上,
null
是一个特殊关键字,而不是标识符,因此您不能将其视为要分配的变量。但是,
undefined
是一个标识符。但是,在非严格
模式和严格
模式下,您都可以创建名称为 undefined 的局部变量。但这是一个糟糕的想法!For the
undefined
type, there is one and only one value:undefined
.For the
null
type, there is one and only one value:null
.So for both of them, the label is both its type and its value.
The difference between them. For example:
null
is an empty valueundefined
is a missing valueOr:
undefined
hasn't had a value yetnull
had a value and doesn't anymoreActually,
null
is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.However,
undefined
is an identifier. In bothnon-strict
mode andstrict
mode, however, you can create a local variable of the name undefined. But this is one terrible idea!我想添加一个知识点,涉及null和undefined之间的细微差别。当您尝试从头开始学习 Vanilla JavaScript(JS) 时,了解这一点是很有必要的:
在编写代码时,这种差异无法识别,因为 null 和 undefined 始终用在右侧( JavaScript 语句的 RHS)。但是,当您在表达式的左侧 (LHS) 使用它们时,您可以轻松观察到这种差异。因此 JS 解释器将以下代码解释为错误:
它给出以下错误:
同时,下面的代码成功运行,尽管我不建议在现实生活中这样做:
这有效,因为 undefined 是全局对象上的一个属性 (window 对象(如果 JavaScript 在浏览器中运行)
I want to add a knowledge point which pertains to a subtle difference between null and undefined. This is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:
While writing code, this difference is not identifiable as both null and undefined are always used in right hand side (RHS) of a JavaScript statement. But when you use them in left hand side (LHS) of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:
It gives below error:
At the same time, below code runs successfully although I won't recommend doing so in real life:
This works because undefined is a property on the global object (window object in case of JavaScript running in a browser)
null 和 undefined 都用来表示某些值的缺失。
a 被初始化并定义。
null 是 JavaScript 中的一个对象
b 是未定义的,未初始化的
未定义对象属性也是未定义的。例如,“x”未在对象 c 上定义,如果您尝试访问 cx,它将返回 undefined。
通常我们将 null 分配给未定义的变量。
null and undefined are both are used to represent the absence of some value.
a is initialized and defined.
null is an object in JavaScript
b is undefined and uninitialized
undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.
Generally we assign null to variables not undefined.
根据 Ryan Morr 关于此主题的详尽文章...
“通常,如果您需要为变量或属性分配非值、将其传递给函数或从函数返回它,则 null 几乎总是最佳选择。简而言之,JavaScript 使用 undefined,程序员应该使用 null。”
请参阅探索空与未定义的永恒深渊
Per Ryan Morr's thorough article on this subject...
"Generally, if you need to assign a non-value to a variable or property, pass it to a function, or return it from a function, null is almost always the best option. To put it simply, JavaScript uses undefined and programmers should use null."
See Exploring the Eternal Abyss of Null and Undefined
在 javascript 中,所有变量都存储为键值对。每个变量都存储为变量名:变量值/引用。
未定义表示变量已在内存中分配了空间,但没有为其分配任何值。作为最佳实践,您不应使用此类型作为作业。
在这种情况下,如何表示您希望变量在代码稍后的位置没有值?您可以使用类型
null ,这也是一种类型,用于定义相同的事物,即没有值,但它与 undefined 不同,因为在这种情况下,您实际上在内存中拥有该值。该值为 null
两者相似,但用法和含义不同。
In javascript all variables are stored as key value pairs. Each variable is stored as variable_name : variable_value/reference.
undefined means a variable has been given a space in memory, but no value is assigned to it. As a best practice, you should not use this type as an assignment.
In that case how to denote when you want a variable to be without value at a later point in the code? You can use the type
null ,which is also a type that is used to define the same thing, absence of a value, but it is not the same as undefined, as in this case you actually have the value in memory. That value is null
Both are similar but usage and meaning are different.
来自Eloquent Javascript一书
From the Eloquent Javascript book
由于 typeof 返回 undefined,undefined 是一种类型,其中 null 是初始化器,表示该变量不指向任何对象(实际上 Javascript 中的所有内容都是对象)。
As typeof returns undefined, undefined is a type where as null is an initializer indicates the variable points to no object(virtually everything in Javascript is an object).
null - 它是一个赋值值,与变量一起使用表示没有值(它是一个对象)。
未定义 - 这是一个没有分配任何值的变量,因此 JavaScript 会为其分配一个未定义的值(它是一种数据类型)。
未声明 - 如果变量根本没有创建,则称为未声明。
null - It is an assignment value, which is used with variable to represent no value (it's an object).
undefined - It is a variable which does not have any value assigned to it, so JavaScript will assign an undefined to it (it's a data type).
undeclared - If a variable is not created at all, it is known as undeclared.
看看这个。输出值千字。
另请参阅:
干杯!
Check this out. The output is worth thousand words.
See also:
Cheers!
一般来说 – 不要使用
null
以避免混淆。undefined
,而不是null
undefined
,然后分配给某个值,然后通过设置为null
来清除。这不一致,最好设置回undefined
。尽管如此,如果框架使用它,或者用于 json 序列化,
null
仍然有意义。Generally – don't use
null
to avoid confusion.undefined
, notnull
undefined
at first, then assigned to some value, then cleared by setting tonull
. That's not consistent, better to set back toundefined
.Still,
null
makes sense if framework uses it, or for json serialization.undefined
和null
之间的差异很小,但还是有区别的。值为未定义
的变量从未被初始化。值为null
的变量被显式指定为null
值,这意味着该变量被显式设置为没有值。如果使用null==undefined
表达式比较undefined
和null
,它们将相等。The difference between
undefined
andnull
is minimal, but there is a difference. A variable whose value isundefined
has never been initialized. A variable whose value isnull
was explicitly given a value ofnull
, which means that the variable was explicitly set to have no value. If you compareundefined
andnull
by using thenull==undefined
expression, they will be equal.基本上,未定义是javascript在运行时创建的全局变量,无论null是否意味着没有值分配给该变量(实际上null本身就是一个对象)。
让我们举个例子:
未定义,这就是您将得到的输出。
现在,
您将得到 5 作为输出。这是未定义和null之间的主要区别
Basically, Undefined is a global variable that javascript create at the run time whether null means that no value has assigned to the variable (actually null is itself an object).
Let's take an example:
Undefined that's what you will get as output.
Now,
and you will get 5 as output. That's the main difference between the Undefined and null