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程序中找到错误?
15 个解决方案
#1
556
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
, false
and the numbers 0
and NaN
哪个将检查空字符串(“”)、null、undefined、false和数字0和NaN
Please note that if you are specifically checking for numbers it is a common mistake to miss 0
with this method, and num !== 0
is preferred (or num !== -1
or ~num
(hacky code that also checks against -1
)) for functions that return -1
, e.g. indexOf
)
请注意,如果您正在特别地检查数字,那么在这种方法中忽略0是一个常见的错误,而对于返回-1的函数,num !== 0是首选的(或者num != -1或~num (hacky代码也检查-1)),例如indexOf)
#2
252
To check for null SPECIFICALLY you would use this:
要检查空值,您可以使用以下方法:
if(variable === null && typeof variable === "object")
...or more simply:
…或者更简单:
if(variable === null)
This test will ONLY pass for null
and will not pass for ""
, undefined
, false
, 0
, or NaN
.
这个测试只会通过null,不会通过“”、未定义、false、0或NaN。
The rest of this is in response to inorganik's comment, Yes, you can check each one individually.
剩下的部分是针对inorgank的评论,是的,您可以逐个检查。
You need to implement use of the absolutely equals: ===
and typeof
to be absolutely sure with your checks.
您需要实现对equals: === =和typeof的使用,以确保您的检查绝对可靠。
I've created a JSFiddle here to show all of the individual tests working
我在这里创建了一个JSFiddle,以显示所有的测试工作。
Here is all of the output of the tests:
以下是所有测试的输出:
Null Test:
if(variable === null && typeof variable === "object")
- 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 === "" && typeof variable === "string")
- 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(variable === undefined && typeof 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 && typeof variable === "boolean")
- 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 && typeof variable === "number")
- 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(!parseFloat(variable) && variable != 0 && typeof variable === "number")
- 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进行测试有点困难;
#3
53
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 sameness for more detail.
更多细节请参见MDN关于平等比较和同一性的文章。
#4
19
Strict equality operator:-
严格平等接线员:-
We can check null by ===
我们可以用===检查null
if ( value === null ){
}
Just by using if
通过使用如果
if( value ) {
}
will evaluate to true if value is not:
如果值不是:
- null
- 零
- undefined
- 未定义的
- NaN
- 南
- empty string ("")
- 空字符串(“”)
- false
- 假
- 0
- 0
#5
4
Firstly, you have a return statement without a function body. Chances are that that will throw an error.
首先,您有一个没有函数体的返回语句。可能会抛出一个错误。
A cleaner way to do your check would be to simply use the ! operator:
一个更干净的方式做你的支票将是简单地使用!接线员:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}
#6
3
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 throw
your own errors. See this.
你也可以抛出你自己的错误。看到这个。
#7
3
to check for undefined and null in javascript you need just to write the following :
要检查javascript中未定义和null,您只需编写以下代码:
if (!var) {
console.log("var IS null or undefined");
} else {
console.log("var is NOT null or undefined");
}
#8
2
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的有理数,比如变量= 0。1,这将失败。一个更好的测试应该是:
if(isNaN(variable) && typeof variable === "number")
#9
2
In JavaScript, no string is equal to null
.
在JavaScript中,没有字符串等于null。
Maybe you expected pass == null
to be true when pass
is an empty string because you're aware that the loose equality operator ==
performs certain kinds of type coercion.
当pass是空字符串时,您可能希望pass == null为真,因为您知道loose equality运算符==执行某些类型强制。
For example, this expression is true:
例如,这个表达是正确的:
'' == 0
In contrast, the strict equality operator ===
says that this is false:
与此相反,严格等式运算符=== =则表示这是错误的:
'' === 0
Given that ''
and 0
are loosely equal, you might reasonably conjecture that ''
and null
are loosely equal. However, they are not.
考虑到“0和0是大致相等的,您可以合理地推测”和null是大致相等的。然而,他们不是。
This expression is false:
这个表达式是错误的:
'' == null
The result of comparing any string to null
is false. Therefore, pass == null
and 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 pass
is 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关于这个主题的文章中的“相同比较”表。
#10
2
Improvement over the accepted answer by explicitly checking for null
but 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");
}
#11
1
underscore: _.isNull
强调:_.isNull
_.isNull(null);
=> true
_.isNull(undefined);
=> false
jQuery: jQuery.type
jQuery:jQuery.type
jQuery.type( null ) === "null"
#12
0
This will not work in case of Boolean values coming from DB for ex:
如果DB的布尔值为例:
value = false
if(!value) {
// it will change all false values to not available
return "not available"
}
#13
-1
Try this:
试试这个:
if (!variable && typeof variable === "object") {
// variable is null
}
#14
-1
You can also use this reusable is-nil open source component which determines whether val
reference is null or undefined and returns a boolean.
您还可以使用这个可重用的is-nil开放源码组件,该组件确定val引用是null还是无定义的,并返回一个布尔值。
Examples:
例子:
isNil(null) // => true
isNil('') // => true
It will return false even if given an empty string for example.
即使给定一个空字符串,它也会返回false。
#15
-2
Please view carefully before downvote.
请在投票前仔细查看。
AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined
. so we can check variable even if it would be an object
holding some instance in place of value.
在JAVASCRIPT中,当一个变量被声明但没有赋值时,它的类型是未定义的。所以我们可以检查变量,即使它是一个对象,它持有一些实例来代替值。
create a helper method for checking nullity that returns true
and use it in your API.
创建一个helper方法,检查返回true的nullity,并在API中使用它。
helper function to check if variable is empty:
辅助函数检查变量是否为空:
function isEmpty(item){
if(item){
return false;
}else{
return true;
}
}
try-catch exceptional API call:
try - catch特殊API调用:
try {
var pass, cpass, email, cemail, user; // only declared but contains nothing.
// parametrs checking
if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
}else{
// do stuff
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log(e.message); // debugging purpose
return true;
} else {
console.log(e.message); // debugging purpose
return true;
}
}
some test cases:
一些测试用例:
var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true
console.log("isEmpty? "+isEmpty(item));
#1
556
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
, false
and the numbers 0
and NaN
哪个将检查空字符串(“”)、null、undefined、false和数字0和NaN
Please note that if you are specifically checking for numbers it is a common mistake to miss 0
with this method, and num !== 0
is preferred (or num !== -1
or ~num
(hacky code that also checks against -1
)) for functions that return -1
, e.g. indexOf
)
请注意,如果您正在特别地检查数字,那么在这种方法中忽略0是一个常见的错误,而对于返回-1的函数,num !== 0是首选的(或者num != -1或~num (hacky代码也检查-1)),例如indexOf)
#2
252
To check for null SPECIFICALLY you would use this:
要检查空值,您可以使用以下方法:
if(variable === null && typeof variable === "object")
...or more simply:
…或者更简单:
if(variable === null)
This test will ONLY pass for null
and will not pass for ""
, undefined
, false
, 0
, or NaN
.
这个测试只会通过null,不会通过“”、未定义、false、0或NaN。
The rest of this is in response to inorganik's comment, Yes, you can check each one individually.
剩下的部分是针对inorgank的评论,是的,您可以逐个检查。
You need to implement use of the absolutely equals: ===
and typeof
to be absolutely sure with your checks.
您需要实现对equals: === =和typeof的使用,以确保您的检查绝对可靠。
I've created a JSFiddle here to show all of the individual tests working
我在这里创建了一个JSFiddle,以显示所有的测试工作。
Here is all of the output of the tests:
以下是所有测试的输出:
Null Test:
if(variable === null && typeof variable === "object")
- 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 === "" && typeof variable === "string")
- 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(variable === undefined && typeof 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 && typeof variable === "boolean")
- 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 && typeof variable === "number")
- 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(!parseFloat(variable) && variable != 0 && typeof variable === "number")
- 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进行测试有点困难;
#3
53
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 sameness for more detail.
更多细节请参见MDN关于平等比较和同一性的文章。
#4
19
Strict equality operator:-
严格平等接线员:-
We can check null by ===
我们可以用===检查null
if ( value === null ){
}
Just by using if
通过使用如果
if( value ) {
}
will evaluate to true if value is not:
如果值不是:
- null
- 零
- undefined
- 未定义的
- NaN
- 南
- empty string ("")
- 空字符串(“”)
- false
- 假
- 0
- 0
#5
4
Firstly, you have a return statement without a function body. Chances are that that will throw an error.
首先,您有一个没有函数体的返回语句。可能会抛出一个错误。
A cleaner way to do your check would be to simply use the ! operator:
一个更干净的方式做你的支票将是简单地使用!接线员:
if (!pass || !cpass || !email || !cemail || !user) {
alert("fill all columns");
}
#6
3
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 throw
your own errors. See this.
你也可以抛出你自己的错误。看到这个。
#7
3
to check for undefined and null in javascript you need just to write the following :
要检查javascript中未定义和null,您只需编写以下代码:
if (!var) {
console.log("var IS null or undefined");
} else {
console.log("var is NOT null or undefined");
}
#8
2
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的有理数,比如变量= 0。1,这将失败。一个更好的测试应该是:
if(isNaN(variable) && typeof variable === "number")
#9
2
In JavaScript, no string is equal to null
.
在JavaScript中,没有字符串等于null。
Maybe you expected pass == null
to be true when pass
is an empty string because you're aware that the loose equality operator ==
performs certain kinds of type coercion.
当pass是空字符串时,您可能希望pass == null为真,因为您知道loose equality运算符==执行某些类型强制。
For example, this expression is true:
例如,这个表达是正确的:
'' == 0
In contrast, the strict equality operator ===
says that this is false:
与此相反,严格等式运算符=== =则表示这是错误的:
'' === 0
Given that ''
and 0
are loosely equal, you might reasonably conjecture that ''
and null
are loosely equal. However, they are not.
考虑到“0和0是大致相等的,您可以合理地推测”和null是大致相等的。然而,他们不是。
This expression is false:
这个表达式是错误的:
'' == null
The result of comparing any string to null
is false. Therefore, pass == null
and 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 pass
is 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关于这个主题的文章中的“相同比较”表。
#10
2
Improvement over the accepted answer by explicitly checking for null
but 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");
}
#11
1
underscore: _.isNull
强调:_.isNull
_.isNull(null);
=> true
_.isNull(undefined);
=> false
jQuery: jQuery.type
jQuery:jQuery.type
jQuery.type( null ) === "null"
#12
0
This will not work in case of Boolean values coming from DB for ex:
如果DB的布尔值为例:
value = false
if(!value) {
// it will change all false values to not available
return "not available"
}
#13
-1
Try this:
试试这个:
if (!variable && typeof variable === "object") {
// variable is null
}
#14
-1
You can also use this reusable is-nil open source component which determines whether val
reference is null or undefined and returns a boolean.
您还可以使用这个可重用的is-nil开放源码组件,该组件确定val引用是null还是无定义的,并返回一个布尔值。
Examples:
例子:
isNil(null) // => true
isNil('') // => true
It will return false even if given an empty string for example.
即使给定一个空字符串,它也会返回false。
#15
-2
Please view carefully before downvote.
请在投票前仔细查看。
AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined
. so we can check variable even if it would be an object
holding some instance in place of value.
在JAVASCRIPT中,当一个变量被声明但没有赋值时,它的类型是未定义的。所以我们可以检查变量,即使它是一个对象,它持有一些实例来代替值。
create a helper method for checking nullity that returns true
and use it in your API.
创建一个helper方法,检查返回true的nullity,并在API中使用它。
helper function to check if variable is empty:
辅助函数检查变量是否为空:
function isEmpty(item){
if(item){
return false;
}else{
return true;
}
}
try-catch exceptional API call:
try - catch特殊API调用:
try {
var pass, cpass, email, cemail, user; // only declared but contains nothing.
// parametrs checking
if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
}else{
// do stuff
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log(e.message); // debugging purpose
return true;
} else {
console.log(e.message); // debugging purpose
return true;
}
}
some test cases:
一些测试用例:
var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true
console.log("isEmpty? "+isEmpty(item));