简体   繁体   English

我想问一下有没有办法缩短这个三元语句?

[英]I would like to ask if there's a way to shorten this ternary statement?

I would like to know the possibilities on how to shorten ternary statement here?我想知道如何在这里缩短三元语句的可能性? TIA TIA

data_items.attributes.promo_banner.promo_join_button_style === 'primary-flat' ? 'primary-flat' : data_items.attributes.promo_banner.promo_join_button_style === 'secondary-flat' ? 'secondary-flat' : data_items.attributes.promo_banner.promo_join_button_style === 'tertiary-flat' ? 'tertiary-flat' : data_items.attributes.promo_banner.promo_join_button_style === 'primary-animated' ? 'primary-animated' : data_items.attributes.promo_banner.promo_join_button_style === 'secondary-animated' ? 'secondary-animated' : data_items.attributes.promo_banner.promo_join_button_style === 'tertiary-animated' ? 'tertiary-animated' : 'error' "

For readability use a shorter variable name to store the value.为了便于阅读,请使用较短的变量名称来存储值。 Then, since you are returning the input value when it matches one of the styles, you can put the styles into an array, and then you can use Array.includes to test them all at once:然后,由于您在输入值与 styles 之一匹配时返回输入值,因此您可以将 styles 放入一个数组中,然后您可以使用Array.includes一次测试它们:

button_styles = ['primary-flat', 'secondary-flat', 'tertiary-flat', 'primary-animated', 'secondary-animated', 'tertiary-animated' ];

promo_button_style = data_items.attributes.promo_banner.promo_join_button_style;

button_styles.includes(promo_button_style) ? promo_button_style : 'error'

Note that for large arrays a Set (with has ) would be more efficient:请注意,对于大型 arrays 一个Set (带有has )会更有效:

button_styles = new Set(['primary-flat', 'secondary-flat', ...])

button_styles.has(promo_button_style) ? promo_button_style : 'error'

You can do something like this:你可以这样做:

const dataStyle = data_items.attributes.promo_banner.promo_join_button_style;

dataStyle === "primary-flat"
  ? "primary-flat"
  : dataStyle === "secondary-flat"
  ? "secondary-flat"
  : dataStyle === "tertiary-flat"
  ? "tertiary-flat"
  : dataStyle === "primary-animated"
  ? "primary-animated"
  : dataStyle === "secondary-animated"
  ? "secondary-animated"
  : dataStyle === "tertiary-animated"
  ? "tertiary-animated"
  : "error";

Btw you should not use such long ternary operators.顺便说一句,您不应该使用如此长的三元运算符。 For such code try using a switch statement.对于此类代码,请尝试使用 switch 语句。

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

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