I worked with ternary operators but never seen before something like that:

.replace('{{name}}', ticket['areaName'] ? ticket['areaName'] : !area && ticket['catName'] ? ticket['catName'] : '--')

Can anyone translate it to human language or standart if else pseudo-code?

有帮助吗?

解决方案

It's just a conditional operator expression where the expression in the third operand is another conditional operator expression:

var temp;
if (ticket['areaName']) {              // First conditional's first operand (test)
    temp = ticket['areaName'];         // First conditional's second operand (true case expression)
}
// All of the following is the first conditional's third operand (the false case expression)
else if (!area && ticket['catName']) { // Second conditional's first operand (test)
    temp = ticket['catName'];          // Second conditional's second operand (true case expression)
}
else {
    temp = '--';                       // Second conditional's third operand (false case expression)
}
/*...*/.replace('{{name}}', temp);

(And yeah, I probably would have broken it up, at least with parens and newlines. No need to make life hard on people trying to read one's code.)

其他提示

Let's prettify your code a little bit, so that you can visualize it easily:

.replace('{{name}}', ticket['areaName']   // if
                        ? ticket['areaName']   // then
                        : !area && ticket['catName']  // else if
                               ? ticket['catName']    // then
                               : '--')                // else

So, basically the 3rd expression of the 1st conditional operator is itself a conditional operator. It's basically an if-else if-else ladder:

var replacement;

if (ticket['areaName']) {
    replacement = ticket['areaName'];
} else if (!area && ticket['catName']) {
    replacement = ticket['catName'];
} else {
    replacement = '--';
}

.replace('{{name}}', replacement);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top