[英]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. 我希望能够将其转换为单个三元语句,其中alert()中的字符串将是返回的值。 I am aware of how to do this for if-elseif-else statements, but not for nested ifs. 我知道如何对if-elseif-else语句执行此操作,但对于嵌套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. 注意- @nderscore问为什么我更改了条件的顺序。 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: 否则,您将开始要么复制对isStandard
的调用,要么进入条件逻辑的这种奇怪的“树”外观层次结构,如下所示:
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.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.