简体   繁体   English

将嵌套的 if else 写入三元运算符

[英]Writing nested if else into ternary operator

I have nested if else statement, is there any solution for turning this into ternary operator?我已经嵌套了 if else 语句,是否有任何解决方案可以将其转换为三元运算符?

let widthStyledMeter;
if (direction === 'horizontal') {
    if(size === "full"){
      widthStyledMeter = '100%';
    }else{
      widthStyledMeter = length;
    }
  } else {
    if(size === "full"){
      widthStyledMeter = '100%';
    }else{
      widthStyledMeter = thickness;
    }
  }

This is how you can use a ternary operator:这是使用三元运算符的方法:

 let widthStyledMeter, direction = "vertical", size = "100%", length = 100, thickness = 20; direction === "horizontal"? (widthStyledMeter = size === "full"? "100%": length): (widthStyledMeter = size === "full"? "100%": thickness); console.log(widthStyledMeter);

Also, since you're sure when size is "full" then widthStyledMeter will always be "100%" , so its better to check size first and then direction .此外,由于您确定size何时为"full" ,那么widthStyledMeter将始终为"100%" ,因此最好先检查size ,然后再检查direction

 let direction = "vertical", size = "100%", length = 100, thickness = 20, widthStyledMeter = size === "full"? "100%": direction === "horizontal"? length: thickness; console.log(widthStyledMeter);

Even though this is way less readable , it would look like this:尽管这不太可读,但它看起来像这样:

const widthStyledMeter = size === "full" ? "100%" : (direction === 'horizontal' ? length : thickness);

You have a common value set here, wich is size == "full" = "100%" , since it's there's no condition on the else statement you can reduce it to avoid a size = "full" double check您在此处设置了一个通用值,即size == "full" = "100%" ,因为 else 语句没有条件,您可以减少它以避免size = "full"双重检查

[Edit] A more readable way would be: [编辑] 更易读的方式是:

let widthStyledMeter;
if (size === "full") {
    widthStyledMeter = "100%";
} else {
    widthStyledMeter = direction === "horizontal" ? length : thickness ;
}

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

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