逗号运算符何时有用? [英] When is the comma operator useful?
问题描述
我在表达式中读到了这个关于逗号运算符的问题(,
)和 MDN docs关于它,但我想不出它有用的场景。
I read this question about the "comma operator" in expressions (,
) and the MDN docs about it, but I can't think of a scenario where it is useful.
那么,逗号运算符何时有用?
So, when is the comma operator useful?
推荐答案
下面的内容可能不是很有用,因为你不是自己编写的,但是minifier可以使用逗号运算符来缩小代码。例如:
The following is probably not very useful as you don't write it yourself, but a minifier can shrink code using the comma operator. For example:
if(x){foo();return bar()}else{return 1}
将成为:
return x?(foo(),bar()):1
? :
运算符现在可以使用,因为逗号运算符(在某种程度上)允许将两个语句写成一个语句。
The ? :
operator can be used now, since the comma operator (to a certain extent) allows for two statements to be written as one statement.
这个是有用的,因为它允许一些整洁的压缩(这里是39 - > 24字节)。
This is useful in that it allows for some neat compression (39 -> 24 bytes here).
我想强调一下 var a,b
中的逗号是 不是 逗号运算符,因为它不存在于表达式中。逗号在 var
语句中具有特殊含义。表达式中的 a,b
将引用这两个变量并计算为 b
,但情况并非如此 var a,b
。
I'd like to stress the fact that the comma in var a, b
is not the comma operator because it doesn't exist within an expression. The comma has a special meaning in var
statements. a, b
in an expression would be referring to the two variables and evaluate to b
, which is not the case for var a, b
.
这篇关于逗号运算符何时有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!