Just bumped into the 开发者_JS百科fact that an if
statement can have multiple parameters in javascript:
// Webkit
if (true, true, false) console.log("this won't get logged");
How well is this supported?
p.s. I get that this is similar to using &&
, but this is interesting and a google couldn't provide the answer.
If statements can't have "multiple parameters". What you observed is the use of the comma operator.
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
Now we see why (true, true, false)
doesn't log anything whereas (true, false, true)
will. As a side note, this syntax is ubiquitously supported (but should almost never be used).
That is not a feature of the if
statement, it's the ,
operator.
You can separate expressions with a comma, and each expression will be evaluated but only the last one is used as value of the whole expressions.
In your example it's pretty useless, but sometimes you want an expression evaluated for it's side effects. Example:
var i = 1;
if (i += 2, i == 3) console.log("this will get logged");
It's not similar to &&
(try moving the false
to the first or second place), it has nothing to do with if
, and it's about as well supported as function literals, i.e. absolutely universally. What you encountered is the comma operator inherited from C, that evaluated the expressions (actually, it's always two expressions and using more conceptually leads to nesting like a + b + c
does) from left to right and throws away all except the last result. The last result becomes the result of the whole expression.
Works in IE7 so I guess this is well supported.
精彩评论