如何检查节点js中的变量是否为空或未定义

问题描述:

我想检查我的数据是否为空或未定义,但即使我的数据不为空,我的 if 块也会执行...

I want to check my data is blank or undefined but my if block execute even my data is not blank ...

代码是:

router.post('/addNewGrade',function(req , res){ 
    var errorMsg = [];  
    console.log(req.body.gradeName)
    if(req.body.gradeName == '' || req.body.gradeName === undefined){
        errorMsg.push("please enter grade name");
    }
    if(req.body.gradeDescription == '' || req.body.gradeDescription === undefined){
        errorMsg.push("please enter description about your grade");
    }
    if(errorMsg !=''){
        res.send({errorMessage :errorMsg}); 
        return;
    }

});

检查变量是否未定义的最佳方法是什么

what is the best way to check variable is undefined or not

因为一个未定义的变量是falsey",你可以简单做

Because an undefined variable is "falsey", you can simple do

if (body.req.gradeName) {
  // do normal stuff
} else {
  // do error stuff
}

或者如果你不需要做任何事情,如果它被定义了,那么你可以做

Or if you don't need to do anything if it is defined, then you can do

if (!(body.req.gradeName)) {
 // do error stuff 
}