【问题标题】:Trying to convert if else statement into ternary in javascript试图在javascript中将if else语句转换为三元
【发布时间】:2021-02-04 14:55:14
【问题描述】:
if (props.name == "Computer"){
        if (result == "Won"){
            result = "Lost";
        }
        else if (result == "Lost"){
            result = "Won";
        }
    }

尝试转换为三进制,但没有成功。 (不知道如何混淆第一行和第二行)。 此外,不确定“不知道该放什么”这个地方。

result =="Won" ? result="Lost": result=="Lost" ? result="Won" : <HAVE NO IDEA WHAT TO PUT>;

【问题讨论】:

  • 为什么需要三元运算符。 if-else 块中的代码更具可读性
  • 只是想练习一下三元算子。

标签: javascript if-statement conditional-operator


【解决方案1】:

您的逻辑中有几种不同的情况。也许你不清楚。但这就是您对三元运算符的尝试所揭示的结果:

  • props.name 可能不是“计算机”。那应该打印什么?
  • result 可能不仅仅是 "Won""Lost"

无论如何,让我们构建这个三元运算符:

result = props.name == "Computer" ? <YOUR CURRENT LOGIC> : <WHATEVER HAPPENS WHEN PROPS IS NOT COMPUTER>;

每当我们遇到您的 if-else 未定义的情况时,我都会让代码按原样返回“结果”:

result = (props.name == "Computer" ? (result == "Won" ? "Lost" : "Won" ) : result);

【讨论】:

  • 哦,是的,如果不满足条件,我想将其保留为结果。有效!谢谢。
【解决方案2】:
result = (props.name == "Computer" ? (result == "Won" ? "Lost" : "Won") : "What you want when props.name is not Computer");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2019-04-09
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2018-10-25
    相关资源
    最近更新 更多