152
Syntax and Language Fundamentals
About the conditional operator and alternative syntax
If you like shortcuts, you can use the conditional (
?:
) operator, also called
conditional
expressions
. The conditional operator lets you convert simple
if..else
statements into a
single line of code. The operator helps decrease the amount of code you write while
accomplishing the same thing, but it also tends to make your ActionScript more difficult
to read.
The following condition is written in long hand, and checks whether the variable
numTwo
is
greater than zero, and returns the result of
numOne/numTwo
or a string of
carrot
:
var numOne:Number = 8;
var numTwo:Number = 5;
if (numTwo > 0) {
trace(numOne / numTwo); // 1.6
} else {
trace("carrot");
}
Using a conditional expression, you would write the same code using this format:
var numOne:Number = 8;
var numTwo:Number = 0;
trace((numTwo > 0) ? numOne/numTwo : "carrot");
As you can see, the shortened syntax reduces readability, and so it is not preferable. If you
must use conditional operators, place the leading condition (before the question mark [
?
])
inside parentheses. This helps improve the readability of your ActionScript. The following
code is an example of ActionScript with improved readability:
var numOne:Number;
(numOne >= 5) ? numOne : -numOne;
You can write a conditional statement that returns a Boolean value, as the following
example shows:
if (cartArr.length > 0) {
return true;
} else {
return false;
}
However, compared with the previous code, the ActionScript in the following example
is preferable:
return (cartArr.length > 0);
The second snippet is shorter and has fewer expressions to evaluate. It’s easier to read
and understand.
Содержание FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH
Страница 1: ...Learning ActionScript 2 0 in Flash...
Страница 8: ...8 Contents...
Страница 18: ...18 Introduction...
Страница 30: ...30 What s New in Flash 8 ActionScript...
Страница 66: ...66 Writing and Editing ActionScript 2 0...
Страница 328: ...328 Interfaces...
Страница 350: ...350 Handling Events...
Страница 590: ...590 Creating Interaction with ActionScript...
Страница 710: ...710 Understanding Security...
Страница 730: ...730 Debugging Applications...
Страница 780: ...780 Deprecated Flash 4 operators...
Страница 830: ...830 Index...