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

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

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

}   

如何在JavaScript程序中查找错误?


当前回答

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

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

//测试let pass=1,cpass=1,email=1,cemail=1,user=1;//只是为了测试if([pass,cpass,email,cemail,user].every(x=>x!==null)){//你的代码在这里。。。console.log(“Yayy!它们都不是空的”);}其他{console.log(“哎呀!至少其中一个为空”);}

其他回答

如果布尔值来自DB,这将不起作用例如:

 value = false

 if(!value) {
   // it will change all false values to not available
   return "not available"
 }

与操作员进行可选检查怎么样?

例如:

// check mother for null or undefined and 
// then if mother exist check her children also
// this 100% sure it support and valid in JS today.
// Apart of that C# have almost the same operator using the same way
if (mother?.children) {

}
else {
 // it is null, undefined, etc...

}

要检查javascript中的undefined和null,只需编写以下内容:

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

检查错误条件:

// Typical API response data
let data = {
  status: true,
  user: [],
  total: 0,
  activity: {sports: 1}
}

// A flag that checks whether all conditions were met or not
var passed = true;

// Boolean check
if (data['status'] === undefined || data['status'] == false){
  console.log("Undefined / no `status` data");
  passed = false;
}

// Array/dict check
if (data['user'] === undefined || !data['user'].length){
  console.log("Undefined / no `user` data");
  passed = false;
}

// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
   console.log("Undefined / no `time` data");
   passed = false;
}

// Other values check
if (data['total'] === undefined || !data['total']){
  console.log("Undefined / no `total` data");
  passed = false;
}

// Passed all tests?
if (passed){
  console.log("Passed all tests");
}

只要在所有地方用==替换==即可。

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

==是严格的相等比较

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