if-else语句的简写 [英] Shorthand for if-else statement

查看:506
本文介绍了if-else语句的简写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,其中包含许多与此类似的if / else语句:

I have some code with a lot of if/else statements similar to this:

var name = "true";

if (name == "true") {
    var hasName = 'Y';
} else if (name == "false") {
    var hasName = 'N';
};

但有没有办法缩短这些陈述?像这样的东西? true:false ...

But is there a way to make these statements shorter? Something like ? "true" : "false" ...

推荐答案

使用三元:? operator [spec]

Using the ternary :? operator [spec].

var hasName = (name === 'true') ? 'Y' :'N';

三元运算符让我们写简写 if..else 语句完全符合您的要求。

The ternary operator lets us write shorthand if..else statements exactly like you want.

看起来像:

(name ==='true') - 我们的条件

- 三元运算符本身

? - the ternary operator itself

'Y' - 条件评估为真的结果

'Y' - the result if the condition evaluates to true

'N' - 条件评估为假的结果

'N' - the result if the condition evaluates to false

所以简而言之(问题) ?(结果如果为true):(结果为假),正如您所看到的 - 它返回表达式的值,因此我们可以简单地将其分配给变量,就像上面的示例中一样。

So in short (question)?(result if true):(result is false) , as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.

这篇关于if-else语句的简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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