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

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

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

}   

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


当前回答

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

例如:

// 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");
}

空值的简单解决方案:

function isEmpty(value) {
        return (
            value === null || value === undefined || value === '' ||
            (Array.isArray(value) && value.length === 0) ||
            (!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0)
        );
    }

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

 value = false

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

实际上,我认为你可能需要使用if(value!==null&&value!==undefined)因为如果使用if(value),也可能会过滤0或false值。

考虑这两个功能:

const firstTest = value => {
    if (value) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}
const secondTest = value => {
    if (value !== null && value !== undefined) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}

firstTest(0);            // result: failed
secondTest(0);           // result: passed

firstTest(false);        // result: failed
secondTest(false);       // result: passed

firstTest('');           // result: failed
secondTest('');          // result: passed

firstTest(null);         // result: failed
secondTest(null);        // result: failed

firstTest(undefined);    // result: failed
secondTest(undefined);   // result: failed

在我的情况下,我只需要检查值是否为null和未定义,我不想过滤0、false或“”值。所以我使用了第二个测试,但你可能也需要过滤它们,这可能会导致你使用第一个测试。

检查错误条件:

// 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");
}