简体   繁体   中英

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

This is the code that I currently have:

        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.");
        }

I want to be able to turn this into a single ternary statement, where the strings inside the alert() will be the value returned. I am aware of how to do this for if-elseif-else statements, but not for nested ifs.

If you really want a ternary...

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

Note that code-readability should trump conciseness in most cases. However, I am not opposed to ternaries as long as they are readable. I personally don't like the lack of readability with this one though. It's starting to edge into that " make me think " category.

Note - @nderscore asked why I changed the order of the conditions. I did it purely to simplify the expression. Otherwise, you start getting into either duplicating the call to isStandard , or getting into this weird "tree" looking hierarchy of conditional logic, like so:

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

I prefer the former... some might prefer the latter.

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") 

Not ternary, but much more readable.

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.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM