如何将带有嵌套if语句的if-else语句转换为一个三元语句

How can I turn an if-else statement with a nested if statement into one ternary statement?

本文关键字:语句 一个 三元 if-else 嵌套 if 转换      更新时间:2023-09-26

这是我目前拥有的代码:

        if (isStandard(statement)) {
            if (isPerfect(statement)) {
                alert("This is a perfect palindrome.");
            } else {
                alert("This is a standard palindrome.");
            }
        } else {
            alert("The statement is not a palindrome.");
        }

我希望能够将其转换为单个三元语句,其中alert()中的字符串将是返回的值。我知道如何为if-elseif-else语句执行此操作,但不知道如何为嵌套的if执行此操作。

如果您真的想要一个三元。。。

alert(
    !isStandard(statement) ? "The statement is not a palindrome." : 
    isPerfect(statement) ? "This is a perfect palindrome." : 
    "This is a standard palindrome.");

请注意,在大多数情况下,代码可读性应该胜过简洁性。然而,我并不反对燕鸥,只要它们可读。不过,我个人不喜欢这本书缺乏可读性。它开始逐渐进入"让我思考"类别。

注意-@nderscore问我为什么改变条件的顺序。我这么做纯粹是为了简化表达。否则,您将开始复制对isStandard的调用,或者进入这种奇怪的条件逻辑"树"结构,如下所示:

alert(
    isStandard(statement) ? 
        (isPerfect(statement) ? 
            "This is a perfect palindrome." : 
            "This is a standard palindrome.") : 
    "The statement is not a palindrome.");

我更喜欢前者。。。有些人可能更喜欢后者。

var m = [" a perfect ", " a standard ", " not a "];
alert("This is" 
     + (isStandard(statement) 
     ? isPerfect(statement) 
       ? m[0] : m[1] 
     : m[2]) 
     + "palindrone")

var m = [" a perfect ", " a standard ", " not a "];
console.log("This is" + (true ? true ? m[0] : m[1] : m[2]) + "palindrone")

不是三元的,但可读性更强。

switch(number(isStandard(statement)) + number(isPerfect(statement)))
{
      case 2:
          alert("This is a perfect palindrome.");
      case 1:
          alert("This is a standard palindrome.");
      case 0:
          alert("The statement is not a palindrome.");
}