问题
I want to check my data is blank or undefined but my if block execute even my data is not blank ...
Code is :
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
回答1:
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
}
回答2:
You can do it like this
if(typeof variable === 'undefined'){
//Variable isn't defined
}
回答3:
it is working
if(req.body.gradeDescription == '' || req.body.gradeDescription === undefined)
来源:https://stackoverflow.com/questions/34878755/how-to-check-if-variable-is-blank-or-undefined-in-node-js