if(x){foo();和x? foo():0; [英] Difference between if (x) { foo(); } and x ? foo() : 0;

查看:89
本文介绍了if(x){foo();和x? foo():0;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Snippet 1:

Snippet 1:

if ( x ) { 
    foo();
}

Snippet 2:

Snippet 2:

x ? foo() : 0;  

这两个片段有什么区别?

What are the differences between those two snippets?

编辑:更正了语法错误。

更新:顺便说一下,似乎还有更短的符号:

Update: btw, it seems that there is an even shorter notation:

x && foo();


推荐答案

一般来说,如果是一个语句(例如,你不能将它分配给变量)和三元运算符?:是表达式的一部分(产生一个值可以分配给变量)。

Generally, if is a statement (e.g. you can't assign it to a variable) and the ternary operator ?: is part of an expression (yields a value which can be assigned to variables).

此外, if 块可以包含<$ c $组件的语句c>?:只能包含表达式。

Also, the if block can contain statements while the components of ?: can only contain expressions.

在你给出的例子中,没有区别,因为你没有使用结果?:
只有当x是真值时,两个片段才会计算 foo()

In the example you give, there is no difference, since you don't use the result of the ?:. Both snippets evaluate foo() only if x is a true value.

这篇关于if(x){foo();和x? foo():0;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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