JavaScript 检查 null 与 undefined 以及 == 和 === 之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5101948/
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
JavaScript checking for null vs. undefined and difference between == and ===
提问by MUG4N
How do I check a variable if it's
null
orundefined
and what is the difference between thenull
andundefined
?What is the difference between
==
and===
(it's hard to search Google for "===" )?
如何检查一个变量,如果是
null
或undefined
,是什么之间的差异null
和undefined
?==
和===
(很难在 Google 上搜索“===”)有什么区别?
回答by T.J. Crowder
How do I check a variable if it's
null
orundefined
...
我如何检查一个变量,如果它是
null
或undefined
...
Is the variable null
:
是变量null
:
if (a === null)
// or
if (a == null) // but see note below
...but note the latter will also be true if a
is undefined
.
...但请注意,如果a
is ,后者也将成立undefined
。
Is it undefined
:
是吗undefined
:
if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below
...but again, note that the last one is vague; it will also be true if a
is null
.
...但同样,请注意最后一个是模糊的;如果a
是,它也将是真的null
。
Now, despite the above, the usualway to check for those is to use the fact that they're falsey:
现在,尽管有上述情况, 检查这些的通常方法是使用它们是false的事实:
if (!a) {
// `a` is falsey, which includes `undefined` and `null`
// (and `""`, and `0`, and `NaN`, and [of course] `false`)
}
This is defined by ToBooleanin the spec.
...and what is the difference between the
null
andundefined
?
......是什么之间的差异
null
和undefined
?
They're both values usually used to indicate the absence of something. undefined
is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined
; there's a difference between calling a function with the value undefined
for an argument, and leaving that argument off entirely.)
它们都是通常用于表示缺少某些东西的值。undefined
是更通用的一个,用作变量的默认值,直到为它们分配其他值,作为调用函数时未提供的函数参数的值,以及当您询问对象时获得的值对于它没有的属性。但它也可以明确用于所有这些情况。(不具有属性的对象与具有具有值的属性undefined
之间存在差异;调用undefined
具有参数值的函数与完全不使用该参数之间存在差异。)
null
is slightly more specific than undefined
: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null
, not undefined
. And similarly, the DOM's getElementById
operation returns an object reference — either a valid one (if it found the DOM element), or null
(if it didn't).
null
比以下更具体undefined
:它是一个空白对象引用。当然,JavaScript 是松散类型的,但并非所有与 JavaScript 交互的东西都是松散类型的。如果像浏览器中的 DOM 这样的 API 需要一个空白的对象引用,我们使用null
,而不是undefined
。同样,DOM 的getElementById
操作返回一个对象引用——一个有效的(如果它找到了 DOM 元素),或者null
(如果它没有)。
Interestingly (or not), they're their own types. Which is to say, null
is the only value in the Null type, and undefined
is the only value in the Undefined type.
有趣的是(或不是),他们是他们自己的类型。也就是说,null
是Null 类型undefined
的唯一值,也是Undefined 类型的唯一值。
What is the difference between "==" and "==="
“==”和“===”有什么区别
The only difference between them is that ==
will do type coercion to try to get the values to match, and ===
won't. So for instance "1" == 1
is true, because "1"
coerces to 1
. But "1" === 1
is false, because the types don't match. ("1" !== 1
is true.) The first (real) step of ===
is "Are the types of the operands the same?" and if the answer is "no", the result is false
. If the types are the same, it does exactly what ==
does.
它们之间的唯一区别是==
会进行类型强制以尝试使值匹配,而===
不会。所以例如"1" == 1
是真的,因为"1"
强制到1
. 但"1" === 1
是false,因为类型不匹配。("1" !== 1
是真的。)第一个(真正的)步骤===
是“操作数的类型是否相同?” 如果答案为“否”,则结果为false
。如果类型相同,则它的作用完全相同==
。
Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0
is true).
类型强制使用相当复杂的规则并且可能产生令人惊讶的结果(例如,"" == 0
为真)。
More in the spec:
规范中的更多内容:
- Abstract Equality Comparison(
==
, also called "loose" equality) - Strict Equality Comparison(
===
)
回答by Julien Portalier
The difference is subtle.
区别很微妙。
In JavaScript an undefined
variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a;
for instance, then a
will be undefined
, because it was never assigned any value.
在 JavaScript 中,undefined
变量是从未被声明或从未赋值的变量。var a;
例如,假设您声明了,然后a
将是undefined
,因为它从未被分配任何值。
But if you then assign a = null;
then a
will now be null
. In JavaScript null
is an object (try typeof null
in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined
is a value).
但是如果你然后分配a = null;
那么a
现在将是null
. 在 JavaScript 中null
是一个对象(typeof null
如果您不相信我,请在 JavaScript 控制台中尝试),这意味着 null 是一个值(实际上甚至undefined
是一个值)。
Example:
例子:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
这可以证明在函数参数中很有用。您可能希望有一个默认值,但认为 null 是可以接受的。在这种情况下,您可以这样做:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional
parameter doSomething(1, 2) then
optional will be the "three"
string but if you pass doSomething(1, 2, null)
then optional will be null
.
如果省略optional
参数doSomething(1, 2) then
optional 将是"three"
字符串,但如果您通过,doSomething(1, 2, null)
则可选将是null
.
As for the equal ==
and strictly equal ===
comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0"
will return true; while 0 === "0"
will return false, because a number is not a string.
对于相等==
和严格相等===
比较器,第一个是弱类型,而严格相等也会检查值的类型。这意味着0 == "0"
将返回 true;while0 === "0"
将返回 false,因为数字不是字符串。
You may use those operators to check between undefined
an null
. For example:
您可以使用这些运营商之间要检查undefined
的null
。例如:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
最后一种情况很有趣,因为它允许您检查变量是否为 undefined 或 null 而不是其他:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
回答by Tim Down
The specis the place to go for full answers to these questions. Here's a summary:
规范是为这些问题提供完整答案的地方。这是一个总结:
- For a variable
x
, you can:- check whether it's
null
by direct comparison using===
. Example:x === null
- check whether it's
undefined
by either of two basic methods: direct comparison withundefined
ortypeof
. For various reasons, I prefertypeof x === "undefined"
. - check whether it's one of
null
andundefined
by using==
and relying on the slightly arcane type coercion rules that meanx == null
does exactly what you want.
- check whether it's
- The basic difference between
==
and===
is that if the operands are of different types,===
will always returnfalse
while==
will convert one or both operands into the same type using rulesthat lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in thetypeof
comparison above),==
and===
will behave exactly the same.
- 对于变量
x
,您可以:- 检查是否
null
通过直接比较使用===
. 例子:x === null
- 检查它是否是
undefined
通过两种基本方法之一:与undefined
或直接比较typeof
。由于种种原因,我更喜欢typeof x === "undefined"
。 - 检查它是否是一个
null
与undefined
利用==
和依托略有神秘的强制类型转换规则,意味着x == null
你想要做什么。
- 检查是否
==
and之间的基本区别在于===
,如果操作数是不同类型,===
则将始终返回,false
而==
将使用导致一些稍微不直观的行为的规则将一个或两个操作数转换为相同类型。如果操作数的类型相同(例如,两者都是字符串,例如在typeof
上面的比较中),==
并且===
行为将完全相同。
More reading:
更多阅读:
- Angus Croll's Truth, Equality and JavaScript
- Andrea Giammarchi's JavaScript Coercion Demystified
- comp.lang.javascript FAQs: JavaScript Type-Conversion
- Angus Croll 的真理、平等和 JavaScript
- Andrea Giammarchi 的JavaScriptCoercion揭秘
- comp.lang.javascript 常见问题解答:JavaScript 类型转换
回答by Sumit Joshi
How do I check a variable if it's null or undefined
如何检查变量是否为空或未定义
just check if a variable has a valid value like this :
只需检查变量是否具有这样的有效值:
if(variable)
it will return true if variable does't contain :
如果变量不包含,它将返回真:
- null
- undefined
- 0
- false
- "" (an empty string)
- NaN
- 空值
- 不明确的
- 0
- 错误的
- ""(空字符串)
- NaN
回答by kannanrbk
undefined
不明确的
It means the variable is not yet intialized .
这意味着变量尚未初始化。
Example :
例子 :
var x;
if(x){ //you can check like this
//code.
}
equals(==)
等于(==)
It only check value is equals not datatype .
它只检查 value 是否等于而不是 datatype 。
Example :
例子 :
var x = true;
var y = new Boolean(true);
x == y ; //returns true
Because it checks only value .
因为它只检查 value 。
Strict Equals(===)
严格等于(===)
Checks the value and datatype should be same .
检查值和数据类型应该相同。
Example :
例子 :
var x = true;
var y = new Boolean(true);
x===y; //returns false.
Because it checks the datatype x is a primitive type and y is a boolean object .
因为它检查数据类型 x 是原始类型而 y 是布尔对象。
回答by Kamil Kie?czewski
Ad 1. null
is not an identifier for a property of the global object, like undefined
can be
广告 1.null
不是全局对象属性的标识符,例如undefined
可以
let x; // undefined
let y=null; // null
let z=3; // has value
// 'w' // is undeclared
if(!x) console.log('x is null or undefined');
if(!y) console.log('y is null or undefined');
if(!z) console.log('z is null or undefined');
try { if(w) 0 } catch(e) { console.log('w is undeclared') }
// typeof not throw exception for undelared variabels
if(typeof w === 'undefined') console.log('w is undefined');
Ad 2. The ===
check values and types. The ==
dont require same types and made implicit conversion before comparison (using .valueOf()
and .toString()
). Here you have all (src):
广告 2.===
检查值和类型。的==
不要需要相同类型和由隐式转换比较之前(使用.valueOf()
和.toString()
)。在这里你有所有(src):
if
如果
==(its negation !=)
==(它的否定!=)
===(its negation !==)
===(它的否定!==)
回答by DaniDev
If your (logical) check is for a negation (!) and you want to capture both JS null
and undefined
(as different Browsers will give you different results) you would use the less restrictive comparison:
e.g.:
如果您的(逻辑)检查是针对否定(!)并且您想同时捕获 JSnull
和undefined
(因为不同的浏览器会给您不同的结果),您将使用限制较少的比较:例如:
var ItemID = Item.get_id();
if (ItemID != null)
{
//do stuff
}
This will capture both null
and undefined
这将同时捕获null
和undefined
回答by Ravikant
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
尝试不同的逻辑。您可以使用波纹管代码检查所有四(4)个条件以进行验证,例如非空,非空白,非未定义和非零仅在javascript和jquery中使用此代码(!(!(变量)))。
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
//If data has valid value
alert("data "+data);
}
else
{
//If data has null, blank, undefined, zero etc.
alert("data is "+data);
}
}
}