The conditional ternary operator doesn't exist out of the box, but it's pretty easy to create your own version in VBScript:
Function IIf(bClause, sTrue, sFalse)
If CBool(bClause) Then
IIf = sTrue
Else
IIf = sFalse
End If
End Function
You can then use this, as per your example:
lunchLocation = IIf(dayOfTheWeek = "Tuesday", "Fuddruckers", "Food Court")
The advantage of this over using a single line If
/Then
/Else
is that it can be directly concatenated with other strings. Using If
/Then
/Else
on a single line must be the only statement on that line.
There is no error checking on this, and the function expects a well formed expression that can be evaluated to a boolean passed in as the clause. For a more complicated and comprehensive answer see below. Hopefully this simple response neatly demonstrates the logic behind the answer though.
It's also worth noting that unlike a real ternary operator, both the sTrue
and sFalse
parameters will be evaluated regardless of the value of bClause
. This is fine if you use it with strings as in the question, but be very careful if you pass in functions as the second and third parameters!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…