Javascript中的条件运算符 [英] Conditional Operators in Javascript

查看:84
本文介绍了Javascript中的条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用类似语句的条件运算符?

Is it ok to use conditional operators like a statement like so?

(x == y) ? alert("yo!") : alert("meh!");

或者使用它来分配这样的值更正确吗?

Or is it more correct to use it to assign a value like so?

z = (x == y) ? "yo!" : "meh!";

如果像声明一样使用它是不正确的,那么是否可以添加多行像这样的执行代码?为多行代码使用ifthen和switch语句更正确吗?

If it's not incorrect to use it like a statement, then is it possible to add more than one line of code for execution like so? Is it more correct to use ifthen and switch statements for multiple lines of code?

(x == y) ? (alert("yo!"), document.write("woot!")) : (alert("meh!"), document.write("blah!"));


推荐答案

条件运算符是有意简洁的,对分配特别有用:

Conditional operators are intentionally succinct and especially useful for assignments:

var a = x ? 1 : 2;

为了便于阅读,使用它们来有条件地运行函数应该使用IF来完成/ ELSE语句:

Using them to conditionally run functions, while possible, should, for the sake of readability be done using IF/ELSE statements:

// This is possible but IMO not best practice:
X ? doSomething() : doSomethingElse();

虽然啰嗦,但大多数情况下,这是更好的解决方案:

While long-winded, most of the time, this is the better solution:

if (X) {
    doSomething();
} else {
    doSomethingElse();
}

IF / ELSE结构的一个显着优点是可以添加其他任务在每种条件下都有最小的麻烦。

One notable benefit to the IF/ELSE structure is that you can add additional tasks under each condition with minimal hassle.

您的最后一个片段也是可能的,但它看起来有点啰嗦,而且,可能更适合更传统的逻辑结构;比如IF / ELSE块。

Your last snippet is also possible but it looks somewhat long-winded and, again, might be better suited to a more conventional logical structure; like an IF/ELSE block.

也就是说,条件运算符仍然是可读的,例如

That said, a conditional operator can still be readable, e.g.

(something && somethingElse > 2) ?
   doSomeLongFunctionName()
   : doSomeOtherLongFunctionName();

最后,就像许多事情一样,这取决于个人喜好。永远记住你写的代码不只是为了你;其他开发者可能不得不在将来涉及它;尽量让它尽可能可读。

In the end, like many things, it's down to personal preference. Always remember that the code you're writing is not just for you; other developers might have to wade through it in the future; try and make it as readable as possible.

这篇关于Javascript中的条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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