如何在不重复的情况下编写三元运算符(又名if)表达式 [英] How to write a ternary operator (aka if) expression without repeating yourself

查看:65
本文介绍了如何在不重复的情况下编写三元运算符(又名if)表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,类似这样:

var value = someArray.indexOf(3) !== -1 ? someArray.indexOf(3) : 0

有没有更好的方法来写?再说一次,我并没有在寻找以上确切问题的答案,只是一个例子,说明您何时可能在三元运算符表达式中重复了操作数...

Is there a better way to write that? Again, I am not seeking an answer to the exact question above, just an example of when you might have repeated operands in ternary operator expressions...

推荐答案

我个人认为,执行此操作的最佳方法仍然是旧的 if 语句:

Personally I find the best way to do this is still the good old if statement:

var value = someArray.indexOf(3);
if (value === -1) {
  value = 0;
}

这篇关于如何在不重复的情况下编写三元运算符(又名if)表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆