如何在 JavaScript 中检查未定义或 null 变量?

发布于 2024-08-27 21:07:11 字数 551 浏览 4 评论 0 原文

我们经常在 JavaScript 代码中使用以下代码模式

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

是否有一种不太冗长的检查方法可以达到相同的效果?

根据一些论坛和文献的说法,简单来说以下应该具有相同的效果。

if (some_variable)
{
    // Do something with some_variable
}

不幸的是,Firebugsome_variable< 时将此类语句评估为运行时错误/code> 未定义,而第一个就可以了。这只是 Firebug 的(不需要的)行为还是这两种方式之间确实有一些区别?

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

Is there a less verbose way of checking that has the same effect?

According to some forums and literature saying simply the following should have the same effect.

if (some_variable)
{
    // Do something with some_variable
}

Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?

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

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

发布评论

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

评论(29

唐婉 2024-09-03 21:07:11

我认为测试“value is null or undefined”的最有效方法是

if ( some_variable == null ){
  // some_variable is either null or undefined
}

所以这两行是等效的:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

正如中提到的问题是,短变体要求已声明 some_variable ,否则将引发 ReferenceError 。然而,在许多用例中,您可以假设这是安全的:

检查可选参数:

function(foo){
    if( foo == null ) {...}

检查现有对象的属性

if(my_obj.foo == null) {...}

另一方面,typeof 可以处理未声明的全局变量(简单地返回undefined )。然而,正如阿尔森德所解释的那样,这些案例应该减少到最低限度,这是有充分理由的。

注释 2

这个 - 甚至更短 - 变体等效:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

所以

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

注释 3

一般来说,建议使用 ===< /code> 而不是 ==
所提出的解决方案是该规则的一个例外。为此,JSHint 语法检查器 甚至提供了 eqnull 选项。

来自 jQuery 样式指南

应该使用严格的相等检查(===)来支持 ==。唯一的
异常是通过 null 检查 undefined 和 null 时。

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

编辑 2021-03:

现在大多数浏览器
支持空值合并运算符 (??)
逻辑 nullish 赋值 (??=) ,它允许更简洁的方式
如果变量为 null 或未定义,则分配默认值,例如:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

可以写为以下任何形式

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;

I think the most efficient way to test for "value is null or undefined" is

if ( some_variable == null ){
  // some_variable is either null or undefined
}

So these two lines are equivalent:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

check for optional arguments:

function(foo){
    if( foo == null ) {...}

check for properties on an existing object

if(my_obj.foo == null) {...}

On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

Note 2

This - even shorter - variant is not equivalent:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

Note 3

In general it is recommended to use === instead of ==.
The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only
exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

EDIT 2021-03:

Nowadays most browsers
support the Nullish coalescing operator (??)
and the Logical nullish assignment (??=), which allows a more concise way to
assign a default value if a variable is null or undefined, for example:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

can be written as any of these forms

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
过潦 2024-09-03 21:07:11

您必须区分不同情况:

  1. 变量可以是未定义未声明。如果您在 typeof 之外的任何上下文中访问未声明的变量,您将会收到错误。
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

已声明但未初始化的变量是未定义

let foo;
if (foo) //evaluates to false because foo === undefined
  1. 未定义的属性,例如someExistingObj.someUndefProperty。未定义的属性不会产生错误,只会返回 undefined,当转换为布尔值时,其计算结果为 false。所以,如果你不关心
    0false,使用 if(obj.undefProp) 就可以了。基于这个事实有一个常见的习语:

    value = obj.prop ||默认值
    

    这意味着“如果obj具有属性prop,则将其分配给value,否则分配默认值defaultValue”。

    有些人认为这种行为令人困惑,认为它会导致难以发现的错误,并建议使用 in 运算符代替

    value = ('prop' in obj) ? obj.prop : 默认值
    

You have to differentiate between cases:

  1. Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

A variable that has been declared but not initialized is undefined.

let foo;
if (foo) //evaluates to false because foo === undefined
  1. Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about
    0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:

    value = obj.prop || defaultValue
    

    which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

    value = ('prop' in obj) ? obj.prop : defaultValue
    
顾忌 2024-09-03 21:07:11

使用正常相等检查 null 也将针对未定义返回 true。

if (window.variable == null)alert('变量为 null 或未定义');

Checking null with normal equality will also return true for undefined.

if (window.variable == null) alert('variable is null or undefined');

JS Equality

命比纸薄 2024-09-03 21:07:11

这是唯一应使用 ==!= 的情况:

if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')

对于任何其他比较,严格比较器(=== 和应使用 !==)。

This is the only case in which == and != should be used:

if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')

For any other comparisons, the strict comparators (=== and !==) should be used.

小巷里的女流氓 2024-09-03 21:07:11

在像 ES5 和 ES6 这样的新 JavaScript 标准中,你可以直接说

> Boolean(0) //false
> Boolean(null)  //false
> Boolean(undefined) //false

all return false,这类似于 Python 对空变量的检查。
因此,如果您想围绕变量编写条件逻辑,只需

if (Boolean(myvar)){
   // Do something
}

在这里说“null”或“空字符串”或“未定义”即可有效处理。

In newer JavaScript standards like ES5 and ES6 you can just say

> Boolean(0) //false
> Boolean(null)  //false
> Boolean(undefined) //false

all return false, which is similar to Python's check of empty variables.
So if you want to write conditional logic around a variable, just say

if (Boolean(myvar)){
   // Do something
}

here "null" or "empty string" or "undefined" will be handled efficiently.

清泪尽 2024-09-03 21:07:11

如果您尝试引用未声明的变量,则所有 JavaScript 实现都会抛出错误。

对象的属性不受相同条件的约束。如果尚未定义对象属性,则尝试访问它时不会抛出错误。因此,在这种情况下,您可以缩短:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

考虑到

if (myObj.some_property != null)

这一点,并且全局变量可以作为全局对象的属性进行访问(在浏览器中为 window),您可以使用以下内容对于全局变量:

if (window.some_variable != null) {
    // Do something with some_variable
}

在局部作用域中,确保在代码块的顶部声明变量总是有用的,这将节省 typeof 的重复使用。

If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.

Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

to

if (myObj.some_property != null)

With this in mind, and the fact that global variables are accessible as properties of the global object (window in the case of a browser), you can use the following for global variables:

if (window.some_variable != null) {
    // Do something with some_variable
}

In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof.

源来凯始玺欢你 2024-09-03 21:07:11

首先你必须非常清楚你测试的内容。 JavaScript 具有各种隐式转换,以及两种不同类型的相等比较器:=====

测试 nullundefined 的函数 test(val) 应该具有以下特征:

 test(null)         => true
 test(undefined)    => true
 test(0)            => false
 test(1)            => false
 test(true)         => false
 test(false)        => false
 test('s')          => false
 test([])           => false

让我们看看这里的哪些想法实际上通过了我们的测试。测试。

这些有效:

val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null

这些无效:

typeof(val) === 'undefined'
!!val

我创建了一个 jsperf 条目来比较这些方法的正确性和性能。目前结果尚无定论,因为在不同浏览器/平台上的运行还不够。请花一点时间在您的计算机上运行测试!

目前看来,简单的 val == null 测试给出了最好的性能。它也是最短的。如果您想要补码,则可以将测试否定为 val != null

Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator: == and ===.

A function, test(val) that tests for null or undefined should have the following characteristics:

 test(null)         => true
 test(undefined)    => true
 test(0)            => false
 test(1)            => false
 test(true)         => false
 test(false)        => false
 test('s')          => false
 test([])           => false

Let's see which of the ideas here actually pass our test.

These work:

val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null

These do not work:

typeof(val) === 'undefined'
!!val

I created a jsperf entry to compare the correctness and performance of these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!

At present, it seems that the simple val == null test gives the best performance. It's also pretty much the shortest. The test may be negated to val != null if you want the complement.

通知家属抬走 2024-09-03 21:07:11

这是使用数组的另一种方法 includes() 方法:

[undefined, null].includes(value)

here's another way using the Array includes() method:

[undefined, null].includes(value)
止于盛夏 2024-09-03 21:07:11

由于没有一个完整且正确的答案,我将尝试总结:

一般来说,表达式:

if (typeof(variable) != "undefined" && variable != null)

无法简化,因为 variable 可能未声明,因此省略 typeof(variable) ! =“未定义”将导致ReferenceError。但是,您可以根据上下文简化表达式

如果变量全局,您可以简化为:

if (window.variable != null)

如果它是 local,你或许可以避免该变量未声明的情况,并且还可以简化为:

if (variable != null)

如果是对象属性,则不必担心ReferenceError:

if (obj.property != null)

Since there is no single complete and correct answer, I will try to summarize:

In general, the expression:

if (typeof(variable) != "undefined" && variable != null)

cannot be simplified, because the variable might be undeclared so omitting the typeof(variable) != "undefined" would result in ReferenceError. But, you can simplify the expression according to the context:

If the variable is global, you can simplify to:

if (window.variable != null)

If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:

if (variable != null)

If it is object property, you don't have to worry about ReferenceError:

if (obj.property != null)
抱猫软卧 2024-09-03 21:07:11

这也是一种很好的(但很冗长)的方式:

if((someObject.someMember ?? null) === null) {
  // bladiebla
}

发生的事情非常清楚并且很难误解。这非常重要! :-)

这使用 ?? 运算符 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)。如果 someObject.someMember 的值为 nullundefined,则 ?? 运算符将启动并生成值null

说实话,我喜欢这个东西的明确性,但我通常更喜欢 someObject.someMember == null,它更具可读性,熟练的 JS 开发人员可能知道这里发生了什么。

This is also a nice (but verbose) way of doing it:

if((someObject.someMember ?? null) === null) {
  // bladiebla
}

It's very clear what's happening and hard to misunderstand. And that can be VERY important! :-)

This uses the ?? operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator). If the value of someObject.someMember is null or undefined, the ?? operator kicks in and will make the value null.

TBH, I like the explicitness of this thing, but I usualle prefer someObject.someMember == null, it's more readable and skilled JS developers probably know what's going on here.

腻橙味 2024-09-03 21:07:11

这是一个极少数情况下的示例,建议使用 == 而不是 ===。表达式 somevar == null 将为 undefinednull 返回 true,但对于其他所有内容返回 false(如果变量未声明,则返回错误)。

使用 != 将翻转结果,如预期的那样。

现代编辑器不会对使用 ==!= 运算符与 null 发出警告,因为这几乎总是所需的行为。

最常见的比较:

undeffinedVar == null     // true
obj.undefinedProp == null // true
null == null              // true
0 == null                 // false
'0' == null               // false
'' == null                // false

自己尝试一下:

let undefinedVar;
console.table([
    { test : undefinedVar,     result: undefinedVar     == null },
    { test : {}.undefinedProp, result: {}.undefinedProp == null },
    { test : null,             result: null             == null },
    { test : false,            result: false            == null },
    { test : 0,                result: 0                == null },
    { test : '',               result: ''               == null },
    { test : '0',              result: '0'              == null },
]);

This is an example of a very rare occasion where it is recommended to use == instead of ===. Expression somevar == null will return true for undefined and null, but false for everything else (an error if variable is undeclared).

Using the != will flip the result, as expected.

Modern editors will not warn for using == or != operator with null, as this is almost always the desired behavior.

Most common comparisions:

undeffinedVar == null     // true
obj.undefinedProp == null // true
null == null              // true
0 == null                 // false
'0' == null               // false
'' == null                // false

Try it yourself:

let undefinedVar;
console.table([
    { test : undefinedVar,     result: undefinedVar     == null },
    { test : {}.undefinedProp, result: {}.undefinedProp == null },
    { test : null,             result: null             == null },
    { test : false,            result: false            == null },
    { test : 0,                result: 0                == null },
    { test : '',               result: ''               == null },
    { test : '0',              result: '0'              == null },
]);
霞映澄塘 2024-09-03 21:07:11

您只需检查变量是否有值即可。意思是,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

如果您不知道变量是否存在(这意味着它是否已声明),您应该使用 typeof 运算符进行检查。例如

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}

You can just check if the variable has a value or not. Meaning,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}
汹涌人海 2024-09-03 21:07:11

与您所拥有的类似,您可以执行类似

if (some_variable === undefined || some_variable === null) { 的 操作
做事
}

Similar to what you have, you could do something like

if (some_variable === undefined || some_variable === null) {
do stuff
}

不…忘初心 2024-09-03 21:07:11

无论 yyy 未定义或为 null,它都会返回 true

if (typeof yyy == 'undefined' || !yyy) {
    console.log('yes');
} else {
    console.log('no');
}

yes

if (!(typeof yyy == 'undefined' || !yyy)) {
    console.log('yes');
} else {
    console.log('no');
}

no

whatever yyy is undefined or null, it will return true

if (typeof yyy == 'undefined' || !yyy) {
    console.log('yes');
} else {
    console.log('no');
}

yes

if (!(typeof yyy == 'undefined' || !yyy)) {
    console.log('yes');
} else {
    console.log('no');
}

no

我做我的改变 2024-09-03 21:07:11

在浏览器中打开开发者工具,然后尝试下图所示的代码。

Img1
Img2

Open the Developer tools in your browser and just try the code shown in the below image.

Img1
Img2

遇见了你 2024-09-03 21:07:11

如果 if 语句的目的是在为变量赋值之前检查 nullundefined 值,则可以使用 空值合并运算符。根据 caniuse 的数据,应该有大约 85% 的浏览器支持(截至 2021 年 1 月)。该运算符的示例如下所示:

const a = some_variable ?? '';

如果 some_variablenull,这将确保将变量分配给空字符串(或任何其他默认值) >未定义

此运算符最适合您的用例,因为它不会返回其他类型的假值(例如 0'')的默认值。

If the purpose of the if statement is to check for null or undefined values before assigning a value to a variable, you can make use of the Nullish Coalescing Operator. According to the data from caniuse, it should be supported by around 85% of the browsers(as of January 2021). An example of the operator is shown below:

const a = some_variable ?? '';

This will ensure that the variable will be assigned to an empty string (or any other default value) if some_variable is null or undefined.

This operator is most suited for your use case, as it does not return the default value for other types of falsy value such as 0 and ''.

分开我的手 2024-09-03 21:07:11

您可以检查该值是否存在。

if(value){
    // True Condition
}else{
// False Condition
}

如果值不是以下值,上面的代码将计算为 true:

  1. null
  2. undefined
  3. NaN
  4. 空字符串 ("")
  5. 0
  6. false

You can check with this value is present or not.

if(value){
    // True Condition
}else{
// False Condition
}

Above code will evaluate to true if value is not:

  1. null
  2. undefined
  3. NaN
  4. empty string ("")
  5. 0
  6. false
亢潮 2024-09-03 21:07:11

正如其中一个答案中提到的,如果您谈论的是具有全局作用域的变量,那么您可能会很幸运。您可能知道,您全局定义的变量往往会添加到 windows 对象中。您可以利用这一事实,假设您正在访问一个名为 bleh 的变量,只需使用双倒置运算符 (!!),

!!window['bleh'];

当 bleh 尚未声明并赋值时,这将返回 false。

As mentioned in one of the answers, you can be in luck if you are talking about a variable that has a global scope. As you might know, the variables that you define globally tend to get added to the windows object. You can take advantage of this fact so lets say you are accessing a variable called bleh, just use the double inverted operator (!!)

!!window['bleh'];

This would return a false while bleh has not been declared AND assigned a value.

泪冰清 2024-09-03 21:07:11

为了理解,让我们分析一下 Javascript 引擎在转换 undefined 、 null 和 '' (也是一个空字符串)时返回的值是什么。您可以直接在开发者控制台上进行检查。

你可以看到所有都转换为 false ,意味着所有这三个都通过 javascript 假设“不存在”。因此,您无需像下面这样显式检查代码中的所有三个。

if (a === undefined || a === null || a==='') {
    console.log("Nothing");
} else {
    console.log("Something");
}

我还想指出一件事。

Boolean(0) 的结果是什么?

当然是假的。当 0 是预期结果中的有效值时,这会在代码中产生错误。因此,请确保在编写代码时检查这一点。

In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.

enter image description here

You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.

if (a === undefined || a === null || a==='') {
    console.log("Nothing");
} else {
    console.log("Something");
}

Also I want to point out one more thing.

What will be the result of Boolean(0)?

Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.

慢慢从新开始 2024-09-03 21:07:11

使用 Ramda,您只需执行 R.isNil(yourValue)
Lodash 和其他辅助库具有相同的功能。

With Ramda, you can simply do R.isNil(yourValue)
Lodash and other helper libraries have the same function.

oО清风挽发oО 2024-09-03 21:07:11

您可以使用 lodash 库。

_.isNil(value)nullundefined 提供 true

测试 - https://bazinga.tools/lodash

在此处输入图像描述

You can make use of lodash library.

_.isNil(value) gives true for both null and undefined

Test on - https://bazinga.tools/lodash

enter image description here

暗喜 2024-09-03 21:07:11

我已经使用此方法

将 id 保存在某个变量中

var someVariable = document.getElementById("someId");

然后使用 if 条件来完成此操作

if(someVariable === ""){
 //logic
} else if(someVariable !== ""){
 //logic
}

I have done this using this method

save the id in some variable

var someVariable = document.getElementById("someId");

then use if condition

if(someVariable === ""){
 //logic
} else if(someVariable !== ""){
 //logic
}
时光匆匆的小流年 2024-09-03 21:07:11

在 ES5 或 ES6 中,如果您需要多次检查,可以这样做:

const excluded = [null, undefined, ''];

if (!exluded.includes(varToCheck) {
  // it will bee not null, not undefined and not void string
}

In ES5 or ES6 if you need check it several times you cand do:

const excluded = [null, undefined, ''];

if (!exluded.includes(varToCheck) {
  // it will bee not null, not undefined and not void string
}

一桥轻雨一伞开 2024-09-03 21:07:11
let varToCheck = ""; //U have to define variable firstly ,or it throw error
const excluded = [null, undefined, ""];

if (!excluded.includes(varToCheck)) {
  // it will bee not null, not undefined and not void string
  console.log("pass");
} else {
  console.log("fail");
}

例如,我复制 vladernn 的答案进行测试,您也可以单击“复制代码片段以回答”按钮来测试。

let varToCheck = ""; //U have to define variable firstly ,or it throw error
const excluded = [null, undefined, ""];

if (!excluded.includes(varToCheck)) {
  // it will bee not null, not undefined and not void string
  console.log("pass");
} else {
  console.log("fail");
}

for example I copy vladernn's answer to test, u can just click button "Copy snippets to answer" to test too .

小瓶盖 2024-09-03 21:07:11

您可以将以下内容与空合并一起使用

//if statement evaluates to true only for null and undefined falsy values, false for others)

const val = ''; 

if(typeof val !== typeof(val ?? 1)) {
    console.log('Matches only null or undefined');
}else {
    console.log('Any other value');
}

you could use the following with nullish coalescing

//if statement evaluates to true only for null and undefined falsy values, false for others)

const val = ''; 

if(typeof val !== typeof(val ?? 1)) {
    console.log('Matches only null or undefined');
}else {
    console.log('Any other value');
}

分分钟 2024-09-03 21:07:11

测试无效 (if (value == null)) 或非无效 (if (value != null)) 比测试变量的定义状态更简洁。

此外,如果使用布尔值定义变量(或对象属性),则测试 if (value) (或 if( obj.property))来确保变量(或对象属性)是否存在会失败false 值。买者自负:)

Testing nullity (if (value == null)) or non-nullity (if (value != null)) is less verbose than testing the definition status of a variable.

Moreover, testing if (value) (or if( obj.property)) to ensure the existence of your variable (or object property) fails if it is defined with a boolean false value. Caveat emptor :)

不忘初心 2024-09-03 21:07:11

将 undefined 或 null 或 0 与 ES5 和 ES6 标准进行比较的最佳方式

 if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
    // do something
    }

Best way to compare undefined or null or 0 with ES5 and ES6 standards

 if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
    // do something
    }
爱冒险 2024-09-03 21:07:11

您必须定义以下形式的函数:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}

You must define a function of this form:

validate = function(some_variable){
    return(typeof(some_variable) != 'undefined' && some_variable != null)
}
白馒头 2024-09-03 21:07:11

通过使用严格比较运算符可以轻松区分这两个值。

示例代码:

function compare(){
    var a = null; //variable assigned null value
    var b;  // undefined
    if (a === b){
        document.write("a and b have same datatype.");
    }
    else{
        document.write("a and b have different datatype.");
    }   
}

Both values can be easily distinguished by using the strict comparison operator.

Sample Code:

function compare(){
    var a = null; //variable assigned null value
    var b;  // undefined
    if (a === b){
        document.write("a and b have same datatype.");
    }
    else{
        document.write("a and b have different datatype.");
    }   
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文