如何检查变量是否不为空?

发布于 2024-10-05 19:43:50 字数 180 浏览 6 评论 0原文

我知道下面是 JavaScript 中检查变量是否为 null 的两种方法,但我很困惑哪种是最佳实践。

我应该这样做:

if (myVar) {...}

或者

if (myVar !== null) {...}

I know that below are the two ways in JavaScript to check whether a variable is not null, but I’m confused which is the best practice to use.

Should I do:

if (myVar) {...}

or

if (myVar !== null) {...}

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

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

发布评论

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

评论(10

预谋 2024-10-12 19:43:50

它们并不等同。如果 myVartruthy(即在条件条件下计算为 true),第一个将执行 if 语句后面的块),而如果 myVarnull 以外的任何值,第二个将执行该块。

JavaScript 中唯一不真实的值如下(又名 falsy 值):

  • null
  • undefined
  • 0
  • < code>""(空字符串)
  • false
  • NaN

They are not equivalent. The first will execute the block following the if statement if myVar is truthy (i.e. evaluates to true in a conditional), while the second will execute the block if myVar is any value other than null.

The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):

  • null
  • undefined
  • 0
  • "" (the empty string)
  • false
  • NaN
束缚m 2024-10-12 19:43:50

以下是测试变量是否不为 NULL 的方法:

if (myVar !== null) {...}

如果 myVar 不为 null,则将执行该块。如果myVar 未定义或 false 或 0NaN 或其他任何内容。

Here is how you can test if a variable is not NULL:

if (myVar !== null) {...}

the block will be executed if myVar is not null.. it will be executed if myVar is undefined or false or 0 or NaN or anything else..

蓬勃野心 2024-10-12 19:43:50
  • 仅当 myVar 等于:false, 0, "", null, undefined, NaN 时,if(myVar) { code } 中的代码才会执行 或者您从未定义变量 myVar (然后另外代码停止执行并抛出异常)。
  • 仅当 myVar 等于 null 或您从未定义时,if(myVar !== null) {code} 中的代码才会执行它(抛出异常)。

在这里,您拥有所有 (src)

if

在此处输入图像描述

== (其否定!=

在此处输入图像描述

=== (其否定 ! ==)

在此处输入图像描述

  • code inside your if(myVar) { code } will be NOT executed only when myVar is equal to: false, 0, "", null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
  • code inside your if(myVar !== null) {code} will be NOT executed only when myVar is equal to null or you never defined it (throws exception).

Here you have all (src)

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

如梦 2024-10-12 19:43:50

阅读这篇文章:http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/

它有一些关于 JavaScript 的不错的提示但它确实提到的一件事是您应该检查 null ,例如:

if(myvar) { }

它还提到了您可能没有意识到的被认为是“错误”的内容。

Have a read at this post: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/

It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:

if(myvar) { }

It also mentions what's considered 'falsey' that you might not realise.

掌心的温暖 2024-10-12 19:43:50

我刚刚遇到了另一种可能的情况。

我进行了 ajax 调用,并以字符串格式将数据返回为 null。我必须这样检查:

if(value != 'null'){}

所以,null 是一个读为“null”的字符串,而不是真正的 null。

编辑:应该理解的是,我并没有按照它应该做的方式来销售它。我有一个场景,这是唯一可以做到的方法。我不知道为什么......也许编写后端的人错误地呈现了数据,但无论如何,这就是现实生活。看到这个被理解它不太正确的人投了反对票,然后又被真正有帮助的人投了赞成票,这是令人沮丧的。

There is another possible scenario I have just come across.

I did an ajax call and got data back as null, in a string format. I had to check it like this:

if(value != 'null'){}

So, null was a string which read "null" rather than really being null.

EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.

东北女汉子 2024-10-12 19:43:50

if (0) 表示 false,if (-1 或除 0 之外的任何其他数字) 表示 true。以下值不是 true、null、undefined、0、""(空字符串)、false、NaN

永远不要使用像 id 这样的数字类型,

if (id) {}

对于可能值为 0 的 id 类型,我们不能使用 if (id) {},因为 if (0) will 表示 false、无效,我们希望它表示与真实 ID 号一样有效。

因此,对于 id 类型,我们必须使用以下内容:

if ((Id !== undefined) && (Id !== null) && (Id !== "")) {

} else {

}

对于其他字符串类型,我们可以使用 if (string) {},因为 null、未定义、空字符串都会评估为 false,这是正确的。

if (string_type_variable) { }

if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, "" (empty string), false, NaN

never use number type like id as

if (id) {}

for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.

So for id type, we must use following:

if ((Id !== undefined) && (Id !== null) && (Id !== "")) {

} else {

}

for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.

if (string_type_variable) { }
风启觞 2024-10-12 19:43:50

有时,如果甚至没有定义,最好做好准备。
为此,我使用 typeof

if(typeof(variable) !== "undefined") {
    //it exist
    if(variable !== null) {
        //and is not null
    }
    else {
        //but is null
    }
}
else {
    //it doesn't
}

Sometimes if it was not even defined is better to be prepared.
For this I used typeof

if(typeof(variable) !== "undefined") {
    //it exist
    if(variable !== null) {
        //and is not null
    }
    else {
        //but is null
    }
}
else {
    //it doesn't
}
仲春光 2024-10-12 19:43:50

如果 myVar 为 null 则 if 块不执行,否则它将执行。

if (myVar != null) {...}

if myVar is null then if block not execute other-wise it will execute.

if (myVar != null) {...}

白龙吟 2024-10-12 19:43:50

您可以使用以下解决方案,而不是使用多个条件语句。

if(![false, 0, "", null, undefined, NaN].includes(myVar)){

   // It's not a null value

}

Rather than using multiple condition statements you can use below solution.

if(![false, 0, "", null, undefined, NaN].includes(myVar)){

   // It's not a null value

}
过去的过去 2024-10-12 19:43:50

您在此处列出的两个条件语句并不比另一个更好。您的使用取决于具体情况。顺便说一下,第二个示例中有一个拼写错误。感叹号后面只能有一个等号。

第一个示例确定 myVar 中的值是否为 true 并执行 {...} 内部的代码

第二个示例评估 myVar 是否为 true不等于 null,如果这种情况为真,它将在 {...} 内执行您的代码

。我建议查看条件语句以获取更多技术。一旦熟悉了它们,您就可以决定何时需要它们。

The two conditional statements you list here are not better than one another. Your usage depends on the situation. You have a typo by the way in the 2nd example. There should be only one equals sign after the exclamation mark.

The 1st example determines if the value in myVar is true and executes the code inside of the {...}

The 2nd example evaluates if myVar does not equal null and if that case is true it will execute your code inside of the {...}

I suggest taking a look into conditional statements for more techniques. Once you are familiar with them, you can decide when you need them.

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