JavaScript 中何时使用 null 或 undefined?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6429225/
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
When is null or undefined used in JavaScript?
提问by testndtv
I am really confused as to when JavaScript returns null
or undefined
. Also different browsers seem to be returning these differently.
我真的很困惑 JavaScript 何时返回null
或undefined
. 不同的浏览器似乎也以不同的方式返回这些。
Could you please give some examples of null
/undefined
with the browsers that return them.
您能否举一些null
/undefined
以及返回它们的浏览器的示例。
While I am now clear on the undefined
aspect, I am still not 100% clear on null
. Is it similar to a blank value?
虽然我现在在这undefined
方面很清楚,但我仍然不是 100% 清楚null
。它类似于空白值吗?
E.g. You have a text box which does not have any value set. Now when you try to access its value, will it be null
or undefined
and are they similar?
例如,您有一个没有设置任何值的文本框。现在,当您尝试访问它的价值,会是null
或者undefined
,它们是否相似?
采纳答案by kennebec
The DOM methods getElementById()
, nextSibling()
, childNodes[n]
, parentNode()
and so on return null
(defined but having no value) when the call does not return a node object.
当调用不返回节点对象时,DOM 方法getElementById()
、nextSibling()
、等将返回(已定义但没有值)。childNodes[n]
parentNode()
null
The propertyis defined, but the object it refers to does not exist.
该属性的定义,但它指的是对象不存在。
This is one of the few times you may notwant to test for equality-
这是为数不多的几次你可能不希望测试equality-
if(x!==undefined)
will be true for a null value
if(x!==undefined)
为空值时为真
but if(x!= undefined)
will be true (only) for values that are not either undefined
or null
.
但if(x!= undefined)
对于不是undefined
或 的值(仅)为真null
。
回答by Cory Gross
I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.
我发现其中一些答案含糊不清且复杂,我发现确定这些问题的最佳方法是打开控制台并自己测试。
var x;
x == null // true
x == undefined // true
x === null // false
x === undefined // true
var y = null;
y == null // true
y == undefined // true
y === null // true
y === undefined // false
typeof x // 'undefined'
typeof y // 'object'
var z = {abc: null};
z.abc == null // true
z.abc == undefined // true
z.abc === null // true
z.abc === undefined // false
z.xyz == null // true
z.xyz == undefined // true
z.xyz === null // false
z.xyz === undefined // true
null = 1; // throws error: invalid left hand assignment
undefined = 1; // works fine: this can cause some problems
So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined
, making it somewhat unreliable compared to null
. Using the ==
operator, you can reliably use null
and undefined
interchangeably as far as I can tell. However, because of the advantage that null
cannot be redefined, I might would use it when using ==
.
所以这绝对是 JavaScript 更微妙的细微差别之一。如您所见,您可以覆盖 的值undefined
,使其与 相比有些不可靠null
。据我所知==
,使用运算符,您可以可靠地使用null
和undefined
互换。但是,由于null
无法重新定义的优势,我可能会在使用==
.
For example, variable != null
will ALWAYS return false if variable
is equal to either null
or undefined
, whereas variable != undefined
will return false if variable
is equal to either null
or undefined
UNLESS undefined
is reassigned beforehand.
例如,variable != null
如果variable
等于null
or将始终返回 false undefined
,而variable != undefined
如果variable
等于null
or 或undefined
UNLESSundefined
事先重新分配则返回 false 。
You can reliably use the ===
operator to differentiate between undefined
and null
, if you need to make sure that a value is actually undefined
(rather than null
).
如果您需要确保值实际上是(而不是),则可以可靠地使用===
运算符来区分undefined
和。null
undefined
null
According to the ECMAScript 5 spec:
根据 ECMAScript 5 规范:
- Both
Null
andUndefined
are two of the six built in types.
- 这两个
Null
和Undefined
两个内置的类型六。
4.3.9 undefined value
4.3.9 未定义值
primitive value used when a variable has not been assigned a value
未为变量赋值时使用的原始值
4.3.11 null value
4.3.11 空值
primitive value that represents the intentional absence of any object value
表示有意不存在任何对象值的原始值
回答by Bjorn
You get undefined for the various scenarios:
您在各种情况下都未定义:
You declare a variable with var but never set it.
你用 var 声明了一个变量,但从不设置它。
var foo;
alert(foo); //undefined.
You attempt to access a property on an object you've never set.
您尝试访问从未设置过的对象上的属性。
var foo = {};
alert(foo.bar); //undefined
You attempt to access an argument that was never provided.
您尝试访问从未提供的参数。
function myFunction (foo) {
alert(foo); //undefined.
}
As cwolves pointed out in a comment on another answer, functions that don't return a value.
正如 cwolves 在对另一个答案的评论中指出的那样,不返回值的函数。
function myFunction () {
}
alert(myFunction());//undefined
A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object
and undefined is of type undefined
.
通常必须在变量或属性上有意设置空值(请参阅注释以了解它可以在未设置的情况下出现的情况)。此外, null 是 type object
, undefined 是 type undefined
。
I should also note that null is valid in JSON but undefined is not:
我还应该注意到 null 在 JSON 中是有效的,但 undefined 不是:
JSON.parse(undefined); //syntax error
JSON.parse(null); //null
回答by Felix Kling
I might be missing something, but afaik, you get undefined
only
我可能会遗漏一些东西,但是 afaik,你undefined
只能得到
Update:Ok, I missed a lot, trying to complete:
更新:好的,我错过了很多,试图完成:
You get undefined
...
你得到undefined
...
... when you try to access properties of an object that don't exist:
...当您尝试访问不存在的对象的属性时:
var a = {}
a.foo // undefined
... when you have declared a variable but not initialized it:
...当你声明了一个变量但没有初始化它时:
var a;
// a is undefined
... when you access a parameter for which no value was passed:
...当您访问没有传递任何值的参数时:
function foo (a, b) {
// something
}
foo(42); // b inside foo is undefined
... when a function does not return a value:
...当函数不返回值时:
function foo() {};
var a = foo(); // a is undefined
It might be that some built-in functions return null
on some error, but if so, then it is documented. null
is a concrete value in JavaScript, undefined
is not.
可能是某些内置函数null
在某些错误时返回,但如果是这样,则将其记录在案。null
在 JavaScript 中是一个具体的值,undefined
不是。
Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable)
to test whether a value is set or not (both, null
and undefined
evaluate to false
).
通常你不需要区分它们。根据变量的可能值,足以用于if(variable)
测试是否设置了值(两者,null
并undefined
评估为false
)。
Also different browsers seem to be returning these differently.
不同的浏览器似乎也以不同的方式返回这些。
Please give a concrete example.
请举一个具体的例子。
回答by DiegoS
Regarding this topic the specification (ecma-262) is quite clear
关于这个主题,规范 (ecma-262) 非常清楚
I found it really useful and straightforward, so that I share it: - Here you will find Equality algorithm- Here you will find Strict equality algorithm
我发现它非常有用和简单,所以我分享它: - 在这里你会找到平等算法- 在这里你会找到严格平等算法
I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.
我在阅读 Mozilla 开发者网站上的“抽象平等、严格平等和相同价值”时遇到了它,部分相同。
I hope you find it useful.
希望对你有帮助。
回答by Alex
A property, when it has no definition, is undefined. null is an object. It's type is null. undefined is not an object, its type is undefined.
一个属性,当它没有定义时,就是未定义的。null 是一个对象。它的类型为空。undefined 不是一个对象,它的类型是 undefined。
This is a good article explaining the difference and also giving some examples.
这是一篇很好的文章,解释了差异并给出了一些例子。