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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:40:09  来源:igfitidea点击:

JavaScript checking for null vs. undefined and difference between == and ===

javascriptnullundefined

提问by MUG4N

  1. How do I check a variable if it's nullor undefinedand what is the difference between the nulland undefined?

  2. What is the difference between ==and ===(it's hard to search Google for "===" )?

  1. 如何检查一个变量,如果是nullundefined,是什么之间的差异nullundefined

  2. =====(很难在 Google 上搜索“===”)有什么区别?

回答by T.J. Crowder

How do I check a variable if it's nullor undefined...

我如何检查一个变量,如果它是nullundefined...

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 ais undefined.

...但请注意,如果ais ,后者也将成立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 ais 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.

这是由规范中的ToBoolean定义的。

...and what is the difference between the nulland undefined?

......是什么之间的差异nullundefined

They're both values usually used to indicate the absence of something. undefinedis 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 undefinedfor an argument, and leaving that argument off entirely.)

它们都是通常用于表示缺少某些东西的值。undefined是更通用的一个,用作变量的默认值,直到为它们分配其他值,作为调用函数时未提供的函数参数的值,以及当您询问对象时获得的值对于它没有的属性。但它也可以明确用于所有这些情况。(不具有属性的对象与具有具有值的属性undefined之间存在差异;调用undefined具有参数值的函数与完全不使用该参数之间存在差异。)

nullis 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 getElementByIdoperation 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, nullis the only value in the Null type, and undefinedis 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" == 1is true, because "1"coerces to 1. But "1" === 1is false, because the types don't match. ("1" !== 1is 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" === 1false,因为类型不匹配。("1" !== 1是真的。)第一个(真正的)步骤===是“操作数的类型是否相同?” 如果答案为“否”,则结果为false。如果类型相同,则它的作用完全相同==

Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0is true).

类型强制使用相当复杂的规则并且可能产生令人惊讶的结果(例如,"" == 0为真)。

More in the spec:

规范中的更多内容:

回答by Julien Portalier

The difference is subtle.

区别很微妙。

In JavaScript an undefinedvariable is a variable that as never been declared, or never assigned a value. Let's say you declare var a;for instance, then awill be undefined, because it was never assigned any value.

在 JavaScript 中,undefined变量是从未被声明或从未赋值的变量。var a;例如,假设您声明了,然后a将是undefined,因为它从未被分配任何值。

But if you then assign a = null;then awill now be null. In JavaScript nullis an object (try typeof nullin a JavaScript console if you don't believe me), which means that null is a value (in fact even undefinedis 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 optionalparameter doSomething(1, 2) thenoptional will be the "three"string but if you pass doSomething(1, 2, null)then optional will be null.

如果省略optional参数doSomething(1, 2) thenoptional 将是"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 undefinedan null. For example:

您可以使用这些运营商之间要检查undefinednull。例如:

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:

规范是为这些问题提供完整答案的地方。这是一个总结:

  1. For a variable x, you can:

    • check whether it's nullby direct comparison using ===. Example: x === null
    • check whether it's undefinedby either of two basic methods: direct comparison with undefinedor typeof. For various reasons, I prefer typeof x === "undefined".
    • check whether it's one of nulland undefinedby using ==and relying on the slightly arcane type coercion rules that mean x == nulldoes exactly what you want.

  2. The basic difference between ==and ===is that if the operands are of different types, ===will always return falsewhile ==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 the typeofcomparison above), ==and ===will behave exactly the same.
  1. 对于变量x,您可以:

    • 检查是否null通过直接比较使用===. 例子:x === null
    • 检查它是否是undefined通过两种基本方法之一:与undefined或直接比较typeof。由于种种原因,我更喜欢typeof x === "undefined"
    • 检查它是否是一个nullundefined利用==和依托略有神秘的强制类型转换规则,意味着x == null你想要做什么。

  2. ==and之间的基本区别在于===,如果操作数是不同类型,===则将始终返回,false==将使用导致一些稍微不直观的行为的规则将一个或两个操作数转换为相同类型。如果操作数的类型相同(例如,两者都是字符串,例如在typeof上面的比较中),==并且===行为将完全相同。

More reading:

更多阅读:

回答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. nullis not an identifier for a property of the global object, like undefinedcan 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

如果

enter image description here

在此处输入图片说明

==(its negation !=)

==(它的否定!=

enter image description here

在此处输入图片说明

===(its negation !==)

===(它的否定!==

enter image description here

在此处输入图片说明

回答by DaniDev

If your (logical) check is for a negation (!) and you want to capture both JS nulland undefined(as different Browsers will give you different results) you would use the less restrictive comparison: e.g.:

如果您的(逻辑)检查是针对否定(!)并且您想同时捕获 JSnullundefined(因为不同的浏览器会给您不同的结果),您将使用限制较少的比较:例如:

var ItemID = Item.get_id();
if (ItemID != null)
{
 //do stuff
}

This will capture both nulland undefined

这将同时捕获nullundefined

回答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);
}

}

}