为了账号安全,请及时绑定邮箱和手机立即绑定

变量返回“null”而不是 null

变量返回“null”而不是 null

浮云间 2023-06-09 15:51:38
我有一个非常基本的 javascript 函数,我将字符串分成两部分。问题是第二部分是“空”而不是空。所以如果功能不能正常工作请找到下面的代码和 console.logs。为什么会有这种奇怪的行为。先感谢您  extractCredentials(request: Request): any {    const authHeaderValue = request.headers.authorization;    const parts = authHeaderValue.split(' ');    const encryptedCredentails = parts[1];    console.log(typeof encryptedCredentails) // prints string    console.log(encryptedCredentails) // null    console.log(encryptedCredentails.length) // prints 4    if (encryptedCredentails == 'null') {      console.log('null') // prints null    }    else {      console.log('not null') // not executed    }    if (encryptedCredentails) {      console.log('true') // true    }    else {      console.log('false') // not executed    }    return encryptedCredentails  }
查看完整描述

3 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

像这样解析它 JSON.parse(encryptedCredentails) 它返回 null 没有 ''


var encryptedCredentails  = 'null'

console.log(JSON.parse(encryptedCredentails )) //null

 console.log(encryptedCredentails ) //"null"


查看完整回答
反对 回复 2023-06-09
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

您是在空格“”的基础上拆分的,因此它不能为“非空”,因为它也会拆分它



查看完整回答
反对 回复 2023-06-09
?
桃花长相依

TA贡献1860条经验 获得超8个赞

此条件正在检查字符串值“null”,而不是原始类型null

    if (encryptedCredentails == 'null') {.
          console.log('null') // prints null
    }

如果您正在尝试进行空检查,encryptedCredentails那么您的条件应该是以下可能的选项之一:

如果你只是想检查空值,而不是其他空值,那么做一个“严格”的平等检查:

if (encryptedCredentails === null)

如果你想把undefined 0etc etc 当作 `null,那么使用:

if (encryptedCredentails == null)

或者

if (!encryptedCredentails)

查看完整回答
反对 回复 2023-06-09
  • 3 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信