JavaScript 检查 null 与 undefined 以及 == 和 === 之间的区别

发布于 2024-10-19 08:52:59 字数 223 浏览 2 评论 0原文

  1. 如何检查变量是否为 nullundefined 以及 nullundefined 之间的区别 code>?

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

  1. How do I check a variable if it's null or undefined and what is the difference between the null and undefined?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

_失温 2024-10-26 08:52:59

如何检查变量是否为 null未定义...

变量是否为 null

if (a === null)
// or
if (a == null) // but see note below

...但请注意,后者也将是如果a未定义,则为 true。

未定义吗:

if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below

……但再次请注意,最后一个是模糊的;如果anull,它也为真。

现在,尽管有上述情况,检查这些的通常方法是利用它们是错误的事实:

if (!a) {
    // `a` is falsey, which includes `undefined` and `null`
    // (and `""`, and `0`, and `NaN`, and [of course] `false`)
}

这是由 ToBoolean

...nullundefined 之间有什么区别?

它们都是通常用来表示某物不存在的值。 undefined 是更通用的一种,用作变量的默认值,直到它们被分配其他值为止,作为调用函数时未提供的函数参数的值,以及作为当你向一个对象请求它没有的属性时你得到的值。但它也可以在所有这些情况下明确使用。 (不具有属性的对象与具有值为 undefined 的属性之间存在差异;使用参数值 undefined 调用函数之间存在差异,并完全保留该参数。)

nullundefined 稍微具体一些:它是一个空白对象引用。当然,JavaScript 是松散类型的,但并非所有与 JavaScript 交互的东西都是松散类型的。如果像浏览器中的 DOM 这样的 API 需要一个空白的对象引用,我们使用 null,而不是 undefined。同样,DOM 的 getElementById 操作返回一个对象引用 — 要么是一个有效的引用(如果它找到了 DOM 元素),要么是 null(如果没有)。

有趣的是(或没有),他们有自己的类型。也就是说,null 是 Null 类型中的唯一值,而 undefined 是 Undefined 类型中的唯一值。

“==”和“===”有什么区别

它们之间的唯一区别是 == 会进行类型强制以尝试获取匹配的值,而 == = 不会。例如,"1" == 1 为 true,因为 "1" 强制为 1。但是 "1" === 1false,因为类型不匹配。 ("1" !== 1 为 true。)=== 的第一步(真正的)是“操作数的类型是否相同?”如果答案为“否”,则结果为false。如果类型相同,则它的作用与 == 完全相同。

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

规范中的更多内容:

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

Is the variable null:

if (a === null)
// or
if (a == null) // but see note below

...but note the latter will also be true if a is undefined.

Is it 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.

Now, despite the above, the usual way to check for those is to use the fact that they're falsey:

if (!a) {
    // `a` is falsey, which includes `undefined` and `null`
    // (and `""`, and `0`, and `NaN`, and [of course] `false`)
}

This is defined by ToBoolean in the spec.

...and what is the difference between the null and 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.)

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).

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.

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.

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

More in the spec:

谁人与我共长歌 2024-10-26 08:52:59

差异是微妙的。

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

但如果您随后分配 a = null;,则 a 现在将为 null。在 JavaScript 中,null 是一个对象(如果您不相信我,请在 JavaScript 控制台中尝试 typeof null),这意味着 null 是一个值(事实上,甚至 >未定义是一个值)。

示例:

var a;
typeof a;     # => "undefined"

a = null;
typeof null;  # => "object"

这在函数参数中非常有用。您可能想要一个默认值,但认为 null 是可以接受的。在这种情况下,您可以这样做:

function doSomething(first, second, optional) {
    if (typeof optional === "undefined") {
        optional = "three";
    }
    // do something
}

如果省略可选参数doSomething(1, 2),那么可选将是“三”字符串,但是如果您传递doSomething(1, 2, null),则可选将为null

至于相等 == 和严格相等 === 比较器,第一个是弱类型,而严格相等也会检查值的类型。这意味着 0 == "0" 将返回 true;而 0 === "0" 将返回 false,因为数字不是字符串。

您可以使用这些运算符来检查 undefinednull。例如:

null === null            # => true
undefined === undefined  # => true
undefined === null       # => false
undefined == null        # => true

最后一种情况很有趣,因为它允许您检查变量是否未定义或为 null,仅此而已:

function test(val) {
    return val == null;
}
test(null);       # => true
test(undefined);  # => true

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.

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).

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:

function doSomething(first, second, optional) {
    if (typeof optional === "undefined") {
        optional = "three";
    }
    // do something
}

If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be 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.

You may use those operators to check between undefined an null. For example:

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:

function test(val) {
    return val == null;
}
test(null);       # => true
test(undefined);  # => true
七禾 2024-10-26 08:52:59

规范是获取这些问题的完整答案的地方。摘要如下:

  1. 对于变量 x,您可以:
    • 通过使用===直接比较来检查它是否为null。示例:x === null
    • 通过以下两种基本方法之一检查其是否为未定义:直接与undefinedtypeof进行比较。由于各种原因,我更喜欢typeof x === "undefined"
    • 通过使用 == 并依赖于表示 的有点神秘的类型强制规则来检查它是否为 nullundefined 之一x == null 正是您想要的。
  2. ===== 之间的基本区别是,如果操作数的类型不同,=== 将始终返回false== 将使用 规则会导致一些稍微不直观的行为。如果操作数的类型相同(例如都是字符串,如上面的 typeof 比较),则 =====行为将完全相同。

更多阅读:

The spec is 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 null by direct comparison using ===. Example: x === null
    • check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
    • check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.
  2. The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.

More reading:

顾北清歌寒 2024-10-26 08:52:59

如何检查变量是否为 null 或未定义

只需检查变量是否具有有效值,如下所示:

if(variable)

它将返回 true

  • 如果变量不包含: null
  • undefined
  • 0
  • false
  • "" (空字符串)
  • NaN,

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
无风消散 2024-10-26 08:52:59

广告 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');

广告 2. === 检查值和类型。 == 不需要相同的类型,并在比较之前进行隐式转换(使用 .valueOf().toString())。这里你有所有(src):

if

在此处输入图像描述

== (其否定 !=

在此处输入图像描述

=== (其否定 !==)

在此处输入图像描述

Ad 1. null is not an identifier for a property of the global object, like undefined can be

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):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

入画浅相思 2024-10-26 08:52:59

undefined

表示变量尚未初始化。

示例:

var x;
if(x){ //you can check like this
   //code.
}

equals(==)

它仅检查值是否等于而不是数据类型。

示例:

var x = true;
var y = new Boolean(true);
x == y ; //returns true

因为它只检查值。

严格等于(===)

检查值和数据类型应相同。

示例:

var x = true;
var y = new Boolean(true);
x===y; //returns false.

因为它检查数据类型 x 是基本类型并且 y 是布尔对象。

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 .

Example :

var x = true;
var y = new Boolean(true);
x == y ; //returns true

Because it checks only 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 .

固执像三岁 2024-10-26 08:52:59

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

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

这将捕获 nullundefined

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.:

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

This will capture both null and undefined

残龙傲雪 2024-10-26 08:52:59

尝试不同的逻辑。您可以使用下面的代码检查所有四(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);
}

}

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.

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

}

平安喜乐 2024-10-26 08:52:59

您可以简单地使用条件语句来检查变量是否为 null 或未定义。

let var;
if (var===null){
console.log("variable is null");
else if(var===undefined){
console.log("variable is undefined");

未定义表示变量已声明但未赋值
Null 表明某个变量被故意设置为 null;
Undefine 大部分时候是在无意的情况下发生的,而 null 则是出于有意的目的而发生的。

“==”和“===”的区别在于,第一个不比较变量的类型,而第二个也比较变量的类型。
这是两者之间的基本区别。

You can simply use conditional statements to check if the variable is null or undefined.

let var;
if (var===null){
console.log("variable is null");
else if(var===undefined){
console.log("variable is undefined");

Undefined shows that a variable is declared but it is not assigned a value
Null shows that a variable is deliberately set to null;
Undefined happens most of the time in unintentional cases while null happens for intentional purposes.

The difference between "==" and "===" is that the first one does not compare the type of variable while the second one compares the type of variable as well.
That is the basic difference between these two.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文