如何在 JavaScript 中检查空值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6003884/
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 19:51:02  来源:igfitidea点击:

How do I check for null values in JavaScript?

javascriptnullcompare

提问by Mahdi_Nine

How can I check for null values in JavaScript? I wrote the code below but it didn't work.

如何在 JavaScript 中检查空值?我写了下面的代码,但没有用。

if (pass == null || cpass == null || email == null || cemail == null || user == null) {      

    alert("fill all columns");
    return false;  

}   

And how can I find errors in my JavaScript programs?

以及如何在我的 JavaScript 程序中找到错误?

回答by Mark Kahn

Javascript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:

Javascript 在检查“空”值方面非常灵活。我猜你实际上是在寻找空字符串,在这种情况下,这个更简单的代码将起作用:

if(!pass || !cpass || !email || !cemail || !user){

Which will check for empty strings (""), null, undefined, falseand the numbers 0and NaN

它将检查空字符串 ( ""), null, undefined,false以及数字0NaN

Please note that if you are specifically checking for numbers it is a common mistake to miss 0with this method, and num !== 0is preferred (or num !== -1or ~num(hacky code that also checks against -1)) for functions that return -1, e.g. indexOf)

请注意,如果您专门检查数字,则0使用此方法会遗漏一个常见的错误,并且num !== 0首选(num !== -1~num(或(也检查的hacky 代码-1))用于返回的函数-1,例如indexOf

回答by WebWanderer

To check for null SPECIFICALLYyou would use this:

检查null具体你可以使用这样的:

if (variable === null)

This test will ONLYpass for nulland will not pass for "", undefined, false, 0, or NaN.

本次测试将通过了null,也不会通过的""undefinedfalse0,或NaN

Additionally, I've provided absolute checks for each "false-like" value (one that would return true for !variable).

此外,我已经为每个“类似假”的值(会为 返回真值)提供了绝对检查!variable

Note, for some of the absolute checks, you will need to implement use of the absolutely equals: ===and typeof.

请注意,对于某些绝对检查,您将需要实现使用absolutely equals: ===typeof

I've created a JSFiddlehere to show all of the individual tests working

我在这里创建了一个JSFiddle来显示所有单独的测试工作

Here is the output of each check:

这是每个检查的输出:

Null Test:

if (variable === null)

- variable = ""; (false) typeof variable = string

- variable = null; (true) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Empty String Test:

if (variable === '')

- variable = ''; (true) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number




Undefined Test:

if (typeof variable == "undefined")

-- or --

if (variable === undefined)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (true) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



False Test:

if (variable === false)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (true) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (false) typeof variable = number



Zero Test:

if (variable === 0)

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (true) typeof variable = number

- variable = NaN; (false) typeof variable = number



NaN Test:

if (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)

-- or --

if (isNaN(variable))

- variable = ''; (false) typeof variable = string

- variable = null; (false) typeof variable = object

- variable = undefined; (false) typeof variable = undefined

- variable = false; (false) typeof variable = boolean

- variable = 0; (false) typeof variable = number

- variable = NaN; (true) typeof variable = number

As you can see, it's a little more difficult to test against NaN;

如您所见,对 进行测试要困难一些NaN

回答by ic3b3rg

just replace the ==with ===in all places.

只需更换=====在所有地方。

==is a loose or abstract equality comparison

==是松散或抽象的相等比较

===is a strict equality comparison

===是严格相等比较

See the MDN article on Equality comparisons and samenessfor more detail.

有关更多详细信息,请参阅关于平等比较和相同性的 MDN 文章。

回答by Arshid KV

Strict equality operator:-

严格相等运算符:-

We can check null by ===

我们可以通过 ===

if ( value === null ){

}

Just by using if

只需使用 if

if( value ) {

}

will evaluate to true if value is not:

如果value 不是,则评估为 true :

  • null
  • undefined
  • NaN
  • empty string ("")
  • false
  • 0
  • 空值
  • 不明确的
  • NaN
  • 空字符串 ("")
  • 错误的
  • 0

回答by deekshith

Improvement over the accepted answer by explicitly checking for nullbut with a simplified syntax:

通过显式检查null但使用简化的语法来改进已接受的答案:

if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
    // your code here ...
}

// Test
let pass=1, cpass=1, email=1, cemail=1, user=1; // just to test

if ([pass, cpass, email, cemail, user].every(x=>x!==null)) {
    // your code here ...
    console.log ("Yayy! None of them are null");
} else {
    console.log ("Oops! At-lease one of them is null");
}

回答by Joey C.

Firstly, you have a return statement without a function body. Chances are that that will throw an error.

首先,您有一个没有函数体的 return 语句。有可能会抛出错误。

A cleaner way to do your check would be to simply use the ! operator:

一种更简洁的检查方法是简单地使用 ! 操作员:

if (!pass || !cpass || !email || !cemail || !user) {

    alert("fill all columns");

}

回答by DrStrangeLove

you can use try catch finally

你可以使用 try catch 最后

 try {
     document.getElementById("mydiv").innerHTML = 'Success' //assuming "mydiv" is undefined
 } catch (e) {

     if (e.name.toString() == "TypeError") //evals to true in this case
     //do something

 } finally {}   

you can also throwyour own errors. See this.

你也throw可以自己的错误。看到这个

回答by Nejmeddine Jammeli

to check for undefinedand nullin javascript you need just to write the following :

要在 javascript 中检查undefinednull,您只需编写以下内容:

if (!var) {
        console.log("var IS null or undefined");
} else {
        console.log("var is NOT null or undefined");
}

回答by Michael Laszlo

In JavaScript, no string is equal to null.

在 JavaScript 中,没有字符串等于null.

Maybe you expected pass == nullto be true when passis an empty string because you're aware that the loose equality operator ==performs certain kinds of type coercion.

也许您希望pass == nullpass是空字符串时为真,因为您知道松散相等运算符==执行某些类型的强制转换。

For example, this expression is true:

例如,这个表达式为真:

'' == 0

In contrast, the strict equality operator ===says that this is false:

相反,严格相等运算符===表示这是错误的:

'' === 0

Given that ''and 0are loosely equal, you might reasonably conjecture that ''and nullare loosely equal. However, they are not.

鉴于''0大致相等,您可以合理地推测''null大致相等。然而,他们不是。

This expression is false:

这个表达式是错误的:

'' == null

The result of comparing any string to nullis false. Therefore, pass == nulland all your other tests are always false, and the user never gets the alert.

与任何字符串进行比较的结果null为假。因此,pass == null所有其他测试总是错误的,用户永远不会收到警报。

To fix your code, compare each value to the empty string:

要修复您的代码,请将每个值与空字符串进行比较:

pass === ''

If you're certain that passis a string, pass == ''will also work because only an empty string is loosely equal to the empty string. On the other hand, some experts say that it's a good practice to always use strict equality in JavaScript unless you specifically want to do the type coercion that the loose equality operator performs.

如果您确定这pass是一个字符串,pass == ''也可以使用,因为只有空字符串大致等于空字符串。另一方面,一些专家表示,在 JavaScript 中始终使用严格相等是一种很好的做法,除非您特别想要执行松散相等运算符执行的类型强制。

If you want to know what pairs of values are loosely equal, see the table "Sameness comparisons" in the Mozilla article on this topic.

如果您想知道哪些值对大致相等,请参阅有关此主题Mozilla 文章中的“相同性比较”表。

回答by Gabriel

This is a comment on WebWanderer's solution regarding checking for NaN (I don't have enough rep yet to leave a formal comment). The solution reads as

这是对 WebWanderer 关于检查 NaN 的解决方案的评论(我还没有足够的代表发表正式评论)。解决方案如下

if(!parseInt(variable) && variable != 0 && typeof variable === "number")

but this will fail for rational numbers which would round to 0, such as variable = 0.1. A better test would be:

但这对于四舍五入为的有理数将失败0,例如variable = 0.1。更好的测试是:

if(isNaN(variable) && typeof variable === "number")