检查两个变量是否未定义

Check two variables for undefined

本文关键字:变量 是否 未定义 两个 检查      更新时间:2023-09-26

JS:

  var ctoken = req.cookies.user;
  var stoken = req.session.passport.user;
  if(ctoken === 'undefined' || stoken === 'undefined'){
    return res.send('invalid token'); 
  }else{
    if (ctoken.split('_')[0] !== stoken) {
      return res.send('invalid token'); 
    }
  }

ctoken.split('_')[0]

抛出错误:

cannot call split of undefined.

为什么?由于if条件,这不应该发生。

去掉引号:

if (ctoken === undefined || stoken === undefined) {

也许你对一些程序员建议使用

if (typeof something === 'undefined') {

但最好的测试是简单地与undefined进行比较.