如何在 JavaScript 中检查 null 值?

2022-01-25 00:00:00 null comparison compare equality 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){

它将检查空字符串 ("")、nullundefinedfalse 和数字 0NaN.

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

请注意,如果您专门检查数字,使用此方法会错过 0 是一个常见错误,并且首选 num !== 0(或num !== -1~num(也检查 -1 的黑客代码))用于返回 -1 的函数,例如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).

相关文章