JavaScript 中的 null 和 undefined 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5076944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between null and undefined in JavaScript?
提问by
I want to know what the difference is between null
and undefined
in JavaScript.
我想知道JavaScriptnull
和undefined
JavaScript之间的区别。
采纳答案by sebastian
In JavaScript, undefined
means a variable has been declared but has not yet been assigned a value, such as:
在 JavaScript 中,undefined
表示变量已经声明但尚未赋值,例如:
var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined
null
is an assignment value. It can be assigned to a variable as a representation of no value:
null
是一个赋值。可以将它分配给变量作为无值的表示:
var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object
From the preceding examples, it is clear that undefined
and null
are two distinct types: undefined
is a type itself (undefined) while null
is an object.
从前面的例子中,很明显undefined
和null
是两种不同的类型:undefined
是类型本身(未定义),而null
是对象。
null === undefined // false
null == undefined // true
null === null // true
and
和
null = 'value' // ReferenceError
undefined = 'value' // 'value'
回答by ayush
I picked this from here
我从这里选择了这个
The undefined value is a primitive value used when a variable has not been assigned a value.
The null value is a primitive value that represents the null, empty, or non-existent reference.
未定义值是在变量尚未赋值时使用的原始值。
空值是一个原始值,表示空、空或不存在的引用。
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:
当你通过 var 声明一个变量并且不给它一个值时,它的值将是 undefined。就其本身而言,如果您尝试使用 WScript.Echo() 或 alert() 这个值,您将看不到任何内容。但是,如果您向其附加一个空白字符串,那么它会突然出现:
var s;
WScript.Echo(s);
WScript.Echo("" + s);
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:
您甚至可以将未定义的变量与 null 进行比较,反之亦然,条件将为真:
undefined == null
null == undefined
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:
然而,它们被认为是两种不同的类型。虽然 undefined 是一种完全属于它自己的类型,但 null 被认为是一个特殊的对象值。您可以通过使用 typeof() 来查看这一点,它返回一个表示变量一般类型的字符串:
var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));
Running the above script will result in the following output:
运行上述脚本将产生以下输出:
undefined
object
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).
不管它们是不同的类型,如果您尝试访问其中任何一个的成员,它们的行为仍然相同,例如,它们将抛出异常。使用 WSH,您会看到可怕的“'varname' 为空或不是对象”,如果您很幸运的话(但这是另一篇文章的主题)。
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.
您可以明确地将变量设置为未定义,但我强烈建议不要这样做。我建议只将变量设置为 null 并为您忘记设置的东西保留未定义的值。同时,我真的鼓励您始终设置每个变量。JavaScript 的作用域链与 C 风格的语言不同,即使是资深程序员也很容易混淆,将变量设置为 null 是防止基于它的错误的最佳方法。
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.
您将看到 undefined 弹出窗口的另一个实例是使用删除运算符时。我们这些来自 C 世界的人可能会错误地将其解释为破坏一个物体,但事实并非如此。此操作的作用是从数组中删除下标或从对象中删除成员。对于数组,它不会影响长度,而是下标现在被认为是未定义的。
var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);
The result of the above script is:
上面脚本的结果是:
0.) a
1.) undefined
2.) c
You will also get undefined returned when reading a subscript or member that never existed.
读取从未存在的下标或成员时,您也会得到 undefined 返回。
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.
null 和 undefined 之间的区别在于:JavaScript 永远不会将任何内容设置为 null,这通常是我们所做的。虽然我们可以将变量设置为 undefined,但我们更喜欢 null 因为它不是我们曾经做过的事情。当您进行调试时,这意味着任何设置为 null 的内容都是您自己做的,而不是 JavaScript。除此之外,这两个特殊值几乎是等价的。
回答by Sebastian Norr
回答by Mina Gabriel
nullis a special keyword that indicates an absence of value.
null是一个特殊的关键字,表示没有值。
think about it as a value, like:
将其视为一个值,例如:
- "foo" is string,
- true is boolean ,
- 1234 is number,
- null is undefined.
- “foo”是字符串,
- true 是布尔值,
- 1234是数字,
- null 未定义。
undefinedproperty indicates that a variable has not been assigned a value including null too . Like
undefined属性表示变量还没有被赋值,包括 null 。喜欢
var foo;
defined empty variable is null
of datatype undefined
定义的空变量是null
数据类型undefined
Both of them are representing a value of a variable with no value
它们都代表一个 没有值的变量的值
ANDnull
doesn't represent a stringthat has no value - empty string-
与null
不代表字符串没有值-空与字符串
Like
喜欢
var a = '';
console.log(typeof a); // string
console.log(a == null); //false
console.log(a == undefined); // false
Now if
现在如果
var a;
console.log(a == null); //true
console.log(a == undefined); //true
BUT
但
var a;
console.log(a === null); //false
console.log(a === undefined); // true
SOeach one has it own way to use
所以每个人都有自己的使用方式
undefineduse it to compare the variable data type
undefined使用它来比较变量数据类型
nulluse it to empty a value of a variable
null使用它来清空变量的值
var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object
回答by Dmitry Sychov
null: absence of value for a variable; undefined: absence of variable itself;
null:变量没有值;未定义:变量本身不存在;
..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 可以很好地用null隐式初始化新声明的变量,但它没有。
回答by Arup Hore
Please read the following carefully. It shall remove all your doubts regarding the the difference between nulland undefinedin JavaScript. Also you can use the utility function given below to exactly determine types.
请仔细阅读以下内容。它将消除您对JavaScript 中null和undefined之间区别的所有疑虑。您也可以使用下面给出的效用函数来准确确定类型。
In JavaScript we can have following types of variables.
在 JavaScript 中,我们可以有以下类型的变量。
- Undeclared Variables
- Declared but Unassigned Variables
- Variables assigned with literal undefined
- Variables assigned with literal null
- Variables assigned with anything other than undefinedor null
- 未声明的变量
- 已声明但未分配的变量
- 用字面量undefined赋值的变量
- 用文字null赋值的变量
- 分配有undefined或null以外的任何变量的变量
Following explains each of these cases one by one
下面一一解释这些情况
Undeclared Variables: Following holds true for undeclared variables
- Can only be checked by typeof()which returns string 'undefined'
- Cannot be checked with ==or ===or by ifor conditional operator ?(throws Reference Error)
Declared but Unassigned Variables
- typeofreturns string 'undefined'
- ==check with nullreturns true
- ==check with undefinedreturns true
- ===check with nullreturns false
- ===check with undefinedreturns true
- ifor conditional operator ?returns false
Variables assigned with literalundefined: These variables are treated similarly as the Declared But Unassigned Variables.
Variables assigned with literalnull
- typeofreturns string 'object'
- ==check with nullreturns true
- ==check with undefinedreturns true
- ===check with nullreturns true
- ===check with undefinedreturns false
- ifor conditional operator ?returns false
Variables assigned with anything other thanundefinedor null
- typeof returns one of the following strings: 'string','number','boolean','function', 'object','symbol'
未声明的变量:以下适用于未声明的变量
- 只能由typeof()检查,它返回字符串'undefined'
- 不能用==或===或if或条件运算符检查?(抛出参考错误)
已声明但未分配的变量
- typeof返回字符串“未定义”
- ==检查null返回true
- ==检查未定义返回true
- ===检查null返回false
- ===检查未定义返回true
- 如果或条件运算符?返回假
用字面量undefined赋值的变量:这些变量的处理方式与已声明但未赋值的变量类似。
用文字null赋值的变量
- typeof返回字符串“对象”
- ==检查null返回true
- ==检查未定义返回true
- ===检查null返回true
- ===检查未定义返回false
- 如果或条件运算符?返回假
分配有undefined或null以外的任何变量的变量
- typeof 返回以下字符串之一: 'string'、'number'、'boolean'、'function'、'object'、'symbol'
Following provides the algorithm for correct type checking of a variable:
以下提供了正确检查变量类型的算法:
- Check for undeclared/unassigned/assigned withundefinedusing typeof. return if string 'undefined'is returned.
- Check for nullusing ===. return 'null'if true.
- Check for actual type using typeof. return type if not equal to 'object'
- Call Object.prototype.toString.call(o)to determine actual object type. It shall return a string of type '[object ObjectType]'for all the built in Javascript or DOMdefined Objects. For user defined objects it returns '[object Object]'
- 使用typeof检查未声明/未分配/分配为undefined。如果返回字符串'undefined',则返回。
- 使用===检查空值。如果为true则返回'null'。
- 使用typeof检查实际类型。如果不等于“对象”,则返回类型
- 调用Object.prototype.toString.call(o)来确定实际的对象类型。它应该为所有内置的 Javascript 或DOM定义的对象返回一个类型为“[object ObjectType]”的字符串。对于用户定义的对象,它返回'[object Object]'
You can also use the following utility function for determining types. It currently supports all ECMA 262 2017 types.
您还可以使用以下实用程序函数来确定类型。它目前支持所有 ECMA 262 2017 类型。
function TypeOf(o,bReturnConstructor)
{
if(typeof o==='undefined') return 'undefined'
if(o===null) return 'null'
if(typeof o!=='object') return typeof o
var type=Object.prototype.toString.call(o)
switch(type)
{
//Value types:4
case '[object Number]': type='number';break;
case '[object String]': type='string';break;
case '[object Boolean]': type='boolean';break;
case '[object Date]': type='date';break;
//Error Types:7
case '[object Error]': type='error';break;
case '[object EvalError]': type='evalerror';break;
case '[object RangeError]': type='rangeerror';break;
case '[object ReferenceError]': type='referenceerror';break;
case '[object SyntaxError]': type='syntaxerror';break;
case '[object TypeError]': type='typeerror';break;
case '[object URIError]': type='urierror';break;
//Indexed Collection and Helper Types:13
case '[object Array]': type='array';break;
case '[object Int8Array]': type='int8array';break;
case '[object Uint8Array]': type='uint8array';break;
case '[object Uint8ClampedArray]': type='uint8clampedarray';break;
case '[object Int16Array]': type='int16array';break;
case '[object Uint16Array]': type='uint16array';break;
case '[object Int32Array]': type='int32array';break;
case '[object Uint32Array]': type='uint32array';break;
case '[object Float32Array]': type='float32array';break;
case '[object Float64Array]': type='float64array';break;
case '[object ArrayBuffer]': type='arraybuffer';break;
case '[object SharedArrayBuffer]': type='sharedarraybuffer';break;
case '[object DataView]': type='dataview';break;
//Keyed Collection Types:2
case '[object Map]': type='map';break;
case '[object WeakMap]': type='weakmap';break;
//Set Types:2
case '[object Set]': type='set';break;
case '[object WeakSet]': type='weakset';break;
//Operation Types
case '[object RegExp]': type='regexp';break;
case '[object Proxy]': type='proxy';break;
case '[object Promise]': type='promise';break;
case '[object Object]': type='object';
if(bReturnConstructor && o.constructor) type=o.constructor.toString().match(/^function\s*([^\s(]+)/)[1];
break;
default:
type=type.split(' ')[1]
type=type.substr(0,type.length-1)
}
return type
}
回答by Kevin
You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.
您可能认为 undefined 表示系统级、意外或类似错误的值缺失,而 null 表示程序级、正常或预期的值缺失。
via JavaScript:The Definitive Guide
通过 JavaScript:权威指南
回答by BERGUIGA Mohamed Amine
I'll explain undefined
, null
and Uncaught ReferenceError
:
我会解释undefined
,null
并且Uncaught ReferenceError
:
1 - Uncaught ReferenceError
: variable has not been declaredin your script, there is no reference to this varaible
2 - undefined
: Variable declared but does not initialised
3 - null
: Variable declared and is an empty value
1 - Uncaught ReferenceError
:变量尚未在您的脚本中声明,没有对此变量的引用
2 - undefined
:变量已声明但未初始化
3 - null
:变量已声明且为空值
回答by R.G.
nulland undefinedare two distinct object types which have the following in common:
null和undefined是两种不同的对象类型,它们具有以下共同点:
- both can only hold a single value, nulland undefinedrespectively;
- both have no properties or methods and an attempt to read any properties of either will result in a run-time error (for all other objects, you get value undefinedif you try to read a non-existent property);
- values nulland undefinedare considered equal to each other and to nothing else by
==
and!=
operators.
- 两者都只能保存一个值,分别为null和undefined;
- 两者都没有属性或方法,并且尝试读取其中任何一个的任何属性都会导致运行时错误(对于所有其他对象,如果您尝试读取不存在的属性,则会得到未定义的值);
- 值null和undefined被
==
和!=
运算符视为彼此相等,并且不等于其他任何值。
The similarities however end here. For once, there is a fundamental difference in the way how keywords nulland undefinedare implemented. This is not obvious, but consider the following example:
然而,相似之处到此为止。这一次,关键字null和undefined的实现方式存在根本差异。这并不明显,但请考虑以下示例:
var undefined = "foo";
WScript.Echo(undefined); // This will print: foo
undefined, NaNand Infinityare 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.
undefined、NaN和Infinity只是预初始化的“超全局”变量的名称——它们在运行时初始化,可以被具有相同名称的普通全局或局部变量覆盖。
Now, let's try the same thing with null:
现在,让我们用null尝试同样的事情:
var null = "foo"; // This will cause a compile-time error
WScript.Echo(null);
Oops! null, trueand falseare reserved keywords - compiler won't let you use them as variable or property names
哎呀!null、true和false是保留关键字 - 编译器不会让您将它们用作变量或属性名称
Another difference is that undefinedis a primitive type, while nullis an object type (indicating the absense of an object reference). Consider the following:
另一个区别是undefined是原始类型,而null是对象类型(表示缺少对象引用)。考虑以下:
WScript.Echo(typeof false); // Will print: boolean
WScript.Echo(typeof 0); // Will print: number
WScript.Echo(typeof ""); // Will print: string
WScript.Echo(typeof {}); // Will print: object
WScript.Echo(typeof undefined); // Will print: undefined
WScript.Echo(typeof null); // (!!!) Will print: object
Also, there is an important difference in the way nulland undefinedare treated in numeric context:
此外,在数字上下文中处理null和undefined的方式也存在重要差异:
var a; // declared but uninitialized variables hold the value undefined
WScript.Echo(a === undefined); // Prints: -1
var b = null; // the value null must be explicitly assigned
WScript.Echo(b === null); // Prints: -1
WScript.Echo(a == b); // Prints: -1 (as expected)
WScript.Echo(a >= b); // Prints: 0 (WTF!?)
WScript.Echo(a >= a); // Prints: 0 (!!!???)
WScript.Echo(isNaN(a)); // Prints: -1 (a evaluates to NaN!)
WScript.Echo(1*a); // Prints: -1.#IND (in Echo output this means NaN)
WScript.Echo(b >= b); // Prints: -1 (as expected)
WScript.Echo(isNaN(b)); // Prints: 0 (b evaluates to a valid number)
WScript.Echo(1*b); // Prints: 0 (b evaluates to 0)
WScript.Echo(a >= 0 && a <= 0); // Prints: 0 (as expected)
WScript.Echo(a == 0); // Prints: 0 (as expected)
WScript.Echo(b >= 0 && b <= 0); // Prints: -1 (as expected)
WScript.Echo(b == 0); // Prints: 0 (!!!)
nullbecomes 0when 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.
null在算术表达式或数值比较中使用时变为0- 与false类似,它基本上只是一种特殊的“零”。另一方面,undefined是真正的“无”,当您尝试在数字上下文中使用它时,它会变成NaN(“不是数字”)。
Note that nulland undefinedreceive a special treatment from ==
and !=
operators, but you can test true numeric equality of aand bwith the expression (a >= b && a <= b)
.
请注意,null和undefined接受来自==
and!=
运算符的特殊处理,但您可以使用表达式测试a和b 的真数值相等性(a >= b && a <= b)
。
回答by Chris
Undefined means a variable has been declared but has no value:
未定义意味着变量已声明但没有值:
var var1;
alert(var1); //undefined
alert(typeof var1); //undefined
Null is an assignment:
Null 是一个赋值:
var var2= null;
alert(var2); //null
alert(typeof var2); //object