【问题标题】:Question mark statement with semicolon, do multiple things if true带分号的问号语句,如果为真,则执行多项操作
【发布时间】:2021-11-19 09:49:56
【问题描述】:

如果它是真的,我想要一个问号语句和多件事情要做。像这样:

something.includes('read') ? (
    console.log(1);
    console.log(2)
       : console.log(3))

像这样我在; 收到')' expected 错误。 这有可能吗?还是我需要在这里使用 if 语句?我想console.log 1 2 如果是真的。

【问题讨论】:

  • 你为什么要为此使用条件/三元表达式?
  • 使用if 语句。三元运算符的副作用很糟糕。
  • ? :条件运算符,而不是“问号语句”(根本不是语句)。它有时也称为“三元运算符”,但实际上它只是 a 三元运算符(接受三个操作数的运算符)。它目前是 JavaScript 唯一的三元运算符,但可能会改变。

标签: javascript if-statement conditional-operator


【解决方案1】:

这不是条件运算符 (? :) 的用例;只需使用if:

if (something.includes('read')) {
    console.log(1);
    console.log(2);
} else {
    console.log(3);
}

为了完整起见,我将指出可能可以使用条件运算符和逗号运算符 (condition ? (firstThing(), secondThing()) : otherThing()) 来完成上述操作,但请不要这样做。没有充分的理由这样做,而且会损害可读性。

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2023-03-12
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多