简体   繁体   English

尝试弄清楚如何将具有多个条件的长三元运算符转换为长 if 语句

[英]Try to figure it out how to translate a long ternary operator with more than one condition into long if statement

I found online this snippet and I'm trying to figure it out how to translate it in a plan if statement:我在网上找到了这个片段,我试图弄清楚如何在计划 if 语句中翻译它:

return a.price > b.price ? 1 : a.price === b.price ? a.name > b.name ? 1 : -1 : -1;

In my opinion, if I had written an if statement:在我看来,如果我写了一个 if 语句:

if (a.price > b.price) {
    return 1;
} else if (a.price === b.price) {
    return 1;
} else if (a.name > b.name) {
    return 1;
} else {
    return -1;
}

But I'm not quite sure what it means a question mark and right after another question mark, same problem with a colon.但我不太确定问号是什么意思,紧接着另一个问号,冒号也有同样的问题。 I get that, the colon, in this case, could be an else if statement (in that order), but what about the question mark?我明白了,在这种情况下,冒号可能是 else if 语句(按此顺序),但是问号呢? any hint?任何提示?

Your first part is right, but the next isn't.你的第一部分是对的,但下一部分不是。 This:这个:

a.price === b.price ? a.name > b.name ? 1 : -1 : -1;

separated out, looks like:分离出来,看起来像:

a.price === b.price
  ? (
    a.name > b.name
      ? 1
      : -1
    )
  : -1;

The inner conditional is a.name > b.name ? 1 : -1内部条件是a.name > b.name ? 1 : -1 a.name > b.name ? 1 : -1 . a.name > b.name ? 1 : -1

If the prices are not equal, -1 is returned.如果价格不相等,则返回-1 Otherwise, the names are compared.否则,将比较名称。 To translate this correctly:要正确翻译:

if (a.price > b.price) {
  return 1;
}
if (a.price !== b.price) {
  return -1;
}
if (a.name > b.name) {
  return 1;
}
return -1;

If this is being used for a .sort callback, another option which is equivalent to the above is:如果这是用于.sort回调,则与上述等效的另一个选项是:

return a.price - b.price || a.name.localeCompare(b.name)

Grouping it like this will help像这样分组会有所帮助

a.price > b.price ? 1 : (a.price === b.price ? (a.name > b.name ? 1 : -1) : -1)

a.price > b.price ? 1 : x
x = a.price === b.price ? y : -1;
y =  a.name > b.name ? 1 : -1; 

The translated IF ELSE would be翻译后的 IF ELSE 将是

if(a.price > b.price){
    return 1
} else {
    if(a.price === b.price){
        if(a.name > b.name){
            return 1;
        } else {
            return -1;
        }
    } else {
        return -1;
    }
}

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

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