如何在 JavaScript 中检查空值? [英] How do I check for null values in JavaScript?
问题描述
如何在 JavaScript 中检查空值?我写了下面的代码,但没有用.
How can I check for null values in JavaScript? I wrote the code below but it didn't work.
if (pass == null || cpass == null || email == null || cemail == null || user == null) {
alert("fill all columns");
return false;
}
我怎样才能找到 JavaScript 程序中的错误?
And how can I find errors in my JavaScript programs?
推荐答案
JavaScript 在检查null"方面非常灵活.值.我猜你实际上是在寻找空字符串,在这种情况下,这个更简单的代码将起作用:
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:
if(!pass || !cpass || !email || !cemail || !user){
将检查空字符串 (""
)、null
、undefined
、false
和数字 0
和 NaN
.
Which will check for empty strings (""
), null
, undefined
, false
and the numbers 0
and NaN
.
请注意,如果您专门检查数字,使用此方法错过 0
是一个常见错误,而首选 num !== 0
(或对于返回 -1 的函数,
,例如num !== -1
或 ~num
(也检查 -1
的hacky 代码)indexOf
).
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
).
这篇关于如何在 JavaScript 中检查空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!