java三目运算符嵌套_替代JS中的嵌套三元运算符

您的替代方案基本上是:

你不想做

那个 if / else

A switch 与 if / else 合并

我试图提出一个合理的查找映射选项,但它很快就变得不合理了 .

我会去#1,它不是那么大:

if (res.distance == 0) {

word = 'a';

} else if (res.distance == 1 && res.difference > 3) {

word = 'b';

} else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) {

word = 'c';

} else {

word = 'd';

}

如果所有的大括号和垂直大小都打扰你,没有它们,它几乎与条件运算符版本一样简洁:

if (res.distance == 0) word = 'a';

else if (res.distance == 1 && res.difference > 3) word = 'b';

else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) word = 'c';

else word = 'd';

(我不是在提倡这一点,我从不主张在同一条线上放下大括号或将声明放在 if 之后,但其他人则有不同的风格观点 . )

在我看来,#2更笨重,但这可能更像是一种风格评论而不是其他任何东西:

word = 'd';

switch (res.distance) {

case 0:

word = 'a';

break;

case 1:

if (res.difference > 3) {

word = 'b';

}

break;

case 2:

if (res.difference > 5 && String(res.key).length > 5) {

word = 'c';

}

break;

}

最后,我赞成这一点,你可以利用JavaScript的 switch 在B -syntax语言族中不常见的事实: case 语句可以是表达式,并且与源代码顺序中的switch值匹配:

switch (true) {

case res.distance == 0:

word = 'a';

break;

case res.distance == 1 && res.difference > 3:

word = 'b';

break;

case res.distance == 2 && res.difference > 5 && String(res.key).length > 5:

word = 'c';

break;

default:

word = 'd';

break;

}

这有多难啊? :-)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值