In: Categories » Computers and technology » Flash » ActionScript: Checking Equality or Comparing Values
| You want to check if two values are equal. Use the equality (or inequality) or strict equality (or strict inequality) operator to compare two values. To check whether a value is a valid number, use isNaN( ). Equality expressions always return a Boolean value indicating whether the two values are equal. The equality (and inequality) operators come in both regular and strict flavors. The regular equality and inequality operators check whether the two expressions being compared can be resolved to the same value after converting them to the same datatype. For example, note that the string "6" and the number 6 are considered equal because the string "6" is converted to the number 6 before comparison: trace(5 == 6); // Displays: false trace(6 == 6); // Displays: true trace(6 == "6"); // Displays: true trace(5 == "6"); // Displays: false The logical inequality operator (!=) returns false if two values are equal and true if they are not equal. If necessary, the operands are converted to the same datatype before the comparison: trace(5 != 6); // Displays: true trace(6 != 6); // Displays: false trace(6 != "6"); // Displays: false trace(5 != "6"); // Displays: true On the other hand, the strict equality and inequality operators first check whether the values being compared are of the same datatype before performing the comparison. Differences in datatype cause the strict equality operator to return false and the strict inequality operator to return true: trace(6 === 6); // Displays: true trace(6 === "6"); // Displays: false trace(6 !== 6); // Displays: false trace(6 !== "6"); // Displays: true There is a big difference between the assignment operator (=) and the equality operator (==). If you use the assignment operator instead of the equality operator, you change the variable's value rather than testing its current value. Using the wrong operator leads to unexpected results. In the following example, myVar equals 5 at first, so you might expect the subsequent if statement to always evaluate to false, preventing the trace( ) from being executed: var myVar = 5;
// The following code is wrong. It should be if (myVar == 6) instead
if (myVar = 6) {
trace("Rabbits are bunnies.");
}
trace("myVar is " + myVar); // Displays: myVar is 6
However, the example mistakenly uses the assignment operator (=) instead of the equality operator (==). That is, the expression myVar = 6 sets myVar to 6 instead of testing whether myVar is 6. When used in an if clause, the expression myVar = 6 is treated as the number 6. Because any nonzero number used in a test expression converts to the Boolean true, the trace( ) action is called. Replace the test expression with myVar == 6 instead. You can check an item's datatype using the typeof operator, as follows: var myVar = 5;
if (typeof myVar == "number") {
trace("Yippee. It's a number.");
}
But some numeric values are invalid. The following example results in myVar being set equal to NaN (a constant representing invalid numbers, short for "Not-a-Number") because the calculation cannot be performed in a meaningful way: var myVar = 15 - "coffee"; Despite its name, NaN is a recognized value of the number datatype: trace(typeof myVar); // Displays: "number" Therefore, to test if something is not only a number, but a valid number, you might try this: var myVar = 15 - "coffee";
if (typeof myVar == "number") {
// Nice try, but this won't work.
if (myVar != NaN) {
trace("Yippee. It's a number.");
}
}
You can't simply compare a value to the constant NaN to check whether it is a valid number. Instead, you must use the special isNaN( ) function to perform the test. To determine if a number is invalid, use the special isNaN( ) function, as follows: var myVar = 15 - "coffee";
if (isNaN(myVar)) {
trace("Sorry, that is not a valid number.");
}
To test the opposite of a condition (i.e., whether the condition is not true) use the logical NOT operator (!). For example, to check whether a variable contains a valid number, use !isNAN( ), as follows: var myVar = 15 - "coffee";
if (!isNaN(myVar)) {
// The number is not invalid, so it must be a valid number.
trace ("That is a valid number.");
// This jumps to another frame, assuming you've labeled a frame "SuccessScreen".
gotoAndStop ("SuccessScreen");
}
Of course, you can perform comparisons using the well-known comparison operators. For example, you can use the > and < operators to check if one value is less than or greater than another value: trace(5 < 6); // Displays: true trace(5 > 5); // Displays: false Similarly, you can use the >= and <= operators to check if one value is less than or equal to, or greater than or equal to, another value: trace(5 <= 6); // Displays: true trace(5 >= 5); // Displays: true You should also be aware that ActionScript compares different datatypes differently. ActionScript data can be categorized into primitive datatypes (string, number, and Boolean) or composite datatypes (object, movieclip, and array). When you compare primitive datatypes, ActionScript compares them "by value." In this example, myVar and myOtherVar are considered equal because they both contain the value 6. var myVar = 6; var myOtherVar = 6; trace (myVar == myOtherVar); // Displays: true However, when you compare composite datatypes, ActionScript compares them "by reference." Comparing items by reference means that the two items are considered equal only if both point to exactly the same object, not merely to objects with matching contents. For example, two arrays containing exactly the same values are not considered equal: // Create two arrays with the same elements.
arrayOne = new Array("a", "b", "c");
arrayTwo = new Array("a", "b", "c");
trace(arrayOne == arrayTwo); // Displays: false
Two composite items are equal only if they both refer to the identical object, array, or movie clip. For example: // Create a single array
arrayOne = new Array("a", "b", "c");
// Create another variable that references the same array.
arrayOne = arrayTwo;
trace(arrayOne == arrayTwo); // Displays: true
|
legal disclaimer
1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service
Useful tools and features
related articles
Create a custom MovieClip.drawEllipse( ) method using the Drawing API and invoke it on a movie clip. You can create a method of the MovieClip class to draw an ellipse that is very similar to the drawCircle( ) method. In fact, the drawCircle( ) method is merely a degenerate version of drawEllipse( ), in which the radii in the x and y directions are the same. The custom drawEllipse( ) method accepts four parameters: xRadius The radius of the ellipse in the x direction (major axis). yRadius ...
2. ActionScript: Filling a Shape with a Gradient
Use the beginGradientFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. In a gradient fill, there is a graded change in colors. Flash supports linear gradients, in which one color fades into the next from left to right. Flash also supports radial gradients, in which the colors radiate out from a center point. You can initiate a gradient-filled shape using beginGradientFill( ) in the same way you initiate a solid-filled shape with beginFill( ). The difference is that the call to beginGradientFill( ) require...
3. Scripting Masks in Flash
Use the Drawing API to create a shape and then use MovicClip.setMask( ) to apply the mask. Masks can be used to create unique shapes or visual effects. For example, you can use masks to create wipes and transitions or interesting animations in which only the masked portion of the artwork is visible at a given time. You can even create masks that change shape over time, and use them to mask bitmapped graphics (in movie clips). You can use any movie clip as a mask of another movie clip using the setMask( ) method. The setMask( ...
4. Drawing a Triangle using ActionScript
Create a custom MovieClip.drawTriangle( ) method using the Drawing API and invoke it on a movie clip. You can determine and plot the vertices of a triangle given the lengths of two sides and the angle between them. This is a better approach than specifying the lengths of the three sides because knowing the lengths of two sides and the angle between them always determines a triangle, whereas three arbitrary sides may not fit together to make a triangle. The custom drawTriangle( ) method accepts six parameters: ab ...
5. ActionScript: Filling a Shape with a Solid or Translucent Color
Use the beginFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. To draw a filled shape, call beginFill( ) prior to any other drawing methods, including the custom methods you have defined such as drawCircle( ) and drawPolygon( ). Invoke endFill( ) after calling other drawing methods to create the shape. You cannot apply a fill to an existing shape drawn at authoring time or runtime. You must invoke beginFill( ) before drawing the shape to be filled. This example creates a solid blue ...
6. Drawing a rectangle using ActionScript
Create a custom MovieClip.drawSimpleRectangle( ) method using the Drawing API and invoke it on a movie clip. To draw a simple rectangle, specify the stroke's attributes using the lineStyle( ) method and then draw four lines using the lineTo( ) method: // Create rectangle_mc with a depth of 1 on the main timeline. _root.createEmptyMovieClip("rectangle_mc", 1); // Specify a one-pixel, solid, black line. rectangle_mc.lineStyle(1, 0x000000, 100); // Draw four lines to form the perimeter ...
7. How to draw a rectangle with rounded corners
You want to draw a rectangle with rounded corners, an offset, or rotation.Create a custom MovieClip.drawRectangle( ) method using the Drawing API and invoke it on a movie clip. The drawSimpleRectangle( ) method is, as the name suggests, quite simple. Let's create a more complex version that also: Draws a rectangle with a specified angle of rotation Let's you specify the rectangle center's coordinates Can draw a rectangle with rounded corners The drawRectangle( ) method accepts...
8. Reusing and Organizing Code in Flash Movies
You want to reuse code that you've created for one project in another Flash movie. Or you want to write your ActionScript code in an external text editor. Place your ActionScript code in external .as files and use the #include directive to add them to your Flash movies: // Adds all the code within MyActionScriptFile.as to your Flash movie. #include "MyActionScriptFile.as" Use the #include directive to incorporate code from external text files into your Flash movie during compilation from a .fla file ...
9. Drawing a Circle using ActionScript
Create a custom MovieClip.drawCircle( ) method using the Drawing API and invoke it on a movie clip. You can create a circle in ActionScript with eight curves. Fewer curves results in a distorted circle and too many curves hinders performance. Let's create a custom method of the MovieClip class for drawing circles. This method, drawCircle( ), allows for three parameters: radius The radius of the circle x The x coordinate of the circle's center point. If undefined, the circle is centered at x =...










