【问题标题】:Javascript if statement executing even when falseJavascript if 语句即使在 false 时也会执行
【发布时间】:2021-02-10 06:03:01
【问题描述】:

我的一个反应文件中有以下代码。显然 showMentor2 的值为 false,但是在控制台(如下所示)中,“仍然会调用”仍然会打印。有人可以帮我弄清楚发生了什么吗?

  const showMentor2 = userInfo.isMentor;
  console.log(`This is the value of showMentor2 ${showMentor2}`);
  if (showMentor2) {
    console.log('this still gets called');
 }

【问题讨论】:

标签: javascript reactjs if-statement


【解决方案1】:

在您的示例中,false 必须是一个字符串,这就是它通过条件检查的原因(因为'false' 是一个非空字符串)

const showMentor2 = 'false';
console.log(`This is the value of showMentor2 ${showMentor2}`);
if (showMentor2) {
  console.log('this still gets called');
}

为了安全地处理这个问题,将其转换为字符串并与'false' 进行比较,两者都可以使用字符串的假值或布尔值

const showMentor2 = String('false') === 'true';
console.log(`This is the value of showMentor2 ${showMentor2}`);
if (showMentor2) {
  console.log('this still gets called');
}

const showMentor2 = String(false) === 'true';
console.log(`This is the value of showMentor2 ${showMentor2}`);
if (showMentor2) {
  console.log('this still gets called');
}

【讨论】:

    【解决方案2】:

    检查 isMentor 是否为字符串,因为它必须是布尔值才能得到您的期望。

    你可以用这个方法做测试

    console.log(typeof userInfo.isMentor);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2019-05-20
      相关资源
      最近更新 更多