如何检查节点js中的变量是否为空或未定义 [英] how to check if variable is blank or undefined in node js

查看:30
本文介绍了如何检查节点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 
}

这篇关于如何检查节点js中的变量是否为空或未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆