【问题标题】:The IF statement got it wrong? [duplicate]IF 语句弄错了吗? [复制]
【发布时间】:2020-10-07 21:46:22
【问题描述】:

嘿,我是 javascript 的初学者,我遇到了这个问题。似乎 IF 语句将变量识别为它不是的东西。我认为这与 OR 运算符有关?

let variabel = `a variable with random value`;

if (variabel === `a` || `b`){
    console.log(`the variable is the same as a or b`)
} else {
    console.log(`not the same`)
}

所以它确实在控制台中显示the variable is the same as a or b。那么if语句是真的吗?但不是吗?

【问题讨论】:

  • 您的 if 语句正在测试 variable === 'a' OR "b" 是否为真。因为“b”是truthy,所以条件的计算结果为真。
  • 你的表达式被评估为(variabel === `a`) || (`b`)
  • 请记住,在这个用例中,模板字面量不会为您提供任何东西。

标签: javascript if-statement or-operator


【解决方案1】:

正确的语法是:

let variabel = `a variable with random value`;

if (variabel === `a` || variabel === `b`){
    console.log(`the variable is the same as a or b`)
} else {
    console.log(`not the same`)
}

【讨论】:

  • 哎呀,菜鸟的错误。我觉得我会做得更多哈哈
【解决方案2】:

OR的正确用法是这样的

let variabel = `a variable with random value`;

if (variabel === `a` || variabel === `b`){
    console.log(`the variable is the same as a or b`)
} else {
    console.log(`not the same`)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2015-10-19
    • 2014-01-16
    相关资源
    最近更新 更多