繁体   English   中英

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

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

这是我目前拥有的代码:

        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语句执行此操作,但对于嵌套ifs则不行。

如果您真的想要三元...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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