SoFunction
Updated on 2025-04-08

Flex is very practical

[Change the output swf scale, background color or frame rate]
Right-click your project in the "Navigator" window frame > select "Properties" > select "ActionScript Compiler" > enter the command you need in "Additional compiler arguments"
If you want to change the background color, please enter: -default-background-color 0xffffff
【Mouse Coordinates】
mouseX mouseY
[Check variable type and return boolean value]
is
[Check variable type and return type]
typeof
[Check the object type and return the object]
as
【It's a number but not a valid number】
var quantity:Number = 15 - "rabbits";
trace(typeof quantity); //Show: "number" , but it is NaN (not a number)
trace(quantity is Number); //true
trace(quantity != NaN); //false
//Use isNaN() function to detect:
isNaN(quantity); //true
//Detect whether the variable contains a valid number:
!isNaN(quantity); //false
【Cancel the default strict compilation mode】
Right-click your project in the "Navigator" window frame > select "Properties" > select "ActionScript Compiler" > cancel "Enabel compile-time type checking" option
[Principal data types and complex data types are like "value types" and "reference types"]
Primitive data types are similar to passing by value:
var intOne:int = 1;
var intTwo:int = 1;
trace(intOne == intTwo); //true
[Complex data types are similar to passing by reference]
var arrayOne:Array = new Array("a", "b");
var arrayTwo:Array = arrayOne;
trace(arrayOne == arrayTwo); //true
//-----------------------------------
var arrayOne:Array = new Array("a", "b");
var arrayTwo:Array = new Array("a", "b");
trace(arrayOne == arrayTwo); //false
【A little knowledge about optimizing logic AND(&&) and OR(||)】
For logic And(&&):
Unless the first half of the conditional expression is true, ActionScript will no longer calculate the second half of the logical AND operator. If the first half is false, the entire conditional expression must be false, so it will be inefficient to calculate the second half.
For logical OR(||):
Unless the first half of the conditional expression is false, ActionScript will no longer calculate the second half of the logical OR operator. If the first half is true, the entire conditional expression must be true.
Summary: When using logical AND(&&), put the expression with the most likely result to be false in front; when using logical OR(||), put the expression with the most likely result to be true in front.
【Timer class precautions】
Don't think that Timer can be extremely accurate; the time interval between using Timer should not be less than 10 milliseconds.
【private, protected, internal, public access permissions】
private: Only accessed inside the class itself, according to convention, start with "_" when naming private members;
protected: can be accessed by the class itself or any subclass. But this is based on instances. In other words, class instances can access their own protection members or the protection members of the parent class, but cannot access the protection members of other instances of the same class. By convention, when naming protection members, start with "_";
internal: can be accessed by the class itself or any class within the same package;
public: It can be accessed inside the class, or it can be accessed directly from the class when it is declared static.
[A function has unknown number of parameters, use the arguments object or the "...(rest)" symbol to access its parameters]
Note: Using the "...(rest)" parameter will make the arguments object unavailable;
private funciton average():void{
trace(); //Number of output parameters
// The type of arguments is: object, but you can access it like accessing an array
trace(arguments[1]); //Output the second parameter
}
private function average(...argu):void{
trace(argu[1]); //Output the second parameter, the argu parameter name is customized.
}
【Error handling try, catch, finally】
private function tryError():void{
try {
trace("test start-try");
throwError();
}catch(errObject:Error) {
trace("Error message:" + );
trace("test end-catch");
return;
}finally{
trace("Although there is a return method in the catch, the code in finally located behind the return method will still be executed. In fact, whether the return method is in try or in the catch, the code in finally will always be executed");
}
trace("There is already a return before, and it will not be executed here. Unless no error is thrown, so that the code in the catch is not executed");
}
private function throwError():void{
throw new Error("throw an error");
}
【The difference between for...in and for each...in】
Unlike the for...in loop, the iterative variable in the for each...in loop contains the value saved by the attribute, but does not contain the name (or primary key, index) of the attribute.
【Tips for naming package paths】
It would be better to use package names corresponding to the owner and related projects. By convention, the beginning of the package name should be the reverse URL name. For example, if Example Corp() writes some ActionScript3.0 classes, it will put all classes in the package (or subpackage). In this way, if there is another Example Corp() in the UK also writes some ActionScript3.0 classes, as long as you use the package, you can ensure uniqueness.
When a class belongs to a specific application, it should be placed in the application-specific subpackage. For example, Example Corp may have an application called WidgetStore. If the WidgetStore application uses a class called ApplicationManager, this class should be placed in the package, or in the subpackage of the package.
By convention, the package name begins with lowercase letters.
【Implicit withdrawal method (getter) and setting method (setter)】
public function get count():uint {
return _count;
}
public function set count(value:uint):uint {
if(value < 100){
_count = value;
}else {
throw Error();
}
}
[Make sure that the class will never have subclasses, use final]
final public class Example{}
【Usage of super keywords】
super(); //The constructor of the parent class can only be used inside the class instance constructor
; //Call the properties of the parent class, and the properties need to be declared public or protected
(); //Call the method of the parent class, the method needs to be declared public or protected
【Create a constant, use the keyword const instead of var】
static public const EXAMPLE:String = "example";
【Detection player version】

This method does not apply to any Flash Player version before version 8.5.
【Judge client system】

【Detection player type】

Possible values ​​are:
"StandAlone", for standalone Flash Player
"External", for external Flash Player or in test mode
"PlugIn", for Flash Player browser plugin
"ActiveX", for Flash Player ActiveX controls used by Microsoft Internet Explorer
【Detection system language】

【Determine whether the user has enabled IME (Input Method Editor)】

【Detection screen resolution】


[Algorithm for centering the pop-up window]
X = (stage width/2)-(window width/2)
Y = (stage height/2)-(window height/2)
[Control how to match the video with Player, including scaling issues]

Values ​​to choose from:
【Stage alignment】

Values ​​to choose from:
【Hide Flash Player's right-click menu】
= false;
【Detection whether the system has audio function】

[Detection whether the player runs on a system with an MP3 decoder or on a system without an MP3 decoder]
.hasMP3
【Detect whether the player can (true) or cannot (false) play streaming videos】

[Detection whether the player runs on a system that supports (true) embedded video, or on a system that does not support (false) embedded video]

【Detect whether the player can (true) or cannot (false) encode video streams (such as video streams from web cameras)】

【Show the "Security Settings" panel in Flash Player】
();
Options:
[Let .swf of other domains access .swf of this domain]
Add: () to the .swf file in this field
Or use the security policy file "". Before Flash 8, this file must be placed in the root directory of the domain where .swf is located. Now, you can use() to specify the location of the security policy file. The practice of rejecting any domain is to fill in nothing in the <cross-domain-policy> tag, and the security policy file also supports the common character "*":
<?xml version="1.0"?>
<!-- / -->
<cross-domain-policy>
<allow-access-from domain="" />
<allow-access-from domain="*." />
<allow-access-from domain="210.38.196.48" />
<allow-access-from domain="*" />
</cross-domain-policy>
【Conversion between different digits】
parseInt(str:String, radix:uint = 0):Number Returns a decimal number, and the parameter radix represents the cardinality of the number to be analyzed. If radix is ​​omitted, the default is 10, unless the beginning of the string is "0x", "0X" or "0":
trace(parseInt("0x12")); //Set radix to 16, output: 18
trace(parseInt("017")); //Set radix to 8, output: 15
Or use the toString(radix) method of Number, uint and int objects.
【Use () to round a number and round it】
()
trace((204.499)); //Output: 204
trace((401.5)); //Output: 402
[Use () to round down a number, just ignore the decimal points]
trace((204.99)); //Output: 204
[Use () to round a number upwards. As long as the decimal part is not zero, the integer part will be added 1]
trace((401.01)); //Output: 402
【Create a random number】
Use() to generate a pseudo-random number n, where 0 <= n < 1
[Search the number to the nearest decimal point, that is, specify the accuracy]
1. Determine the number of decimal places of the number you want to take: For example, if you want to take 90.337 to 90.34, it means you want to take two decimal places, that is, you want to take the nearest 0.01;
2. Let the input value be divided by the number selected in step 1 (this example is 0.01);
3. Use () to take the value calculated in step 2 into the closest integer;
4. Multiply the result obtained in step 3 by the value used for division in step 2.
For example, to take 90.337 into two decimal places, you can use:
trace((90.337/0.01)*0.01); //Output: 90.34
[Search the number into the closest multiple value of an integer]
Example 1, this will take 92.5 into the most recent multiple of 5:
trace((92.5/5)*5); //Output: 95
Example 2, this will take 92.5 into the most recent multiple of 10:
trace((92.5/10)*10); //Output: 90
【Get random numbers within the specified range of values】
//Desirable range: [min, max]
private function randRange(min:Number, max:Number):Number {
var randomNum:Number = (() * (max - min + 1)) + min;
return randomNum;
}
Application example:
Simulate silver coins, that is, you want to get a random boolean value (true or false): randRange(0, 1);
Simulate dice rolling, that is, you want to get six random values: randRange(1, 6);
To avoid being cached, a unique number is needed to be appended to the end of the URL. Usually the best way is to get the current number of milliseconds.
【Conversion between radians and degree】
Convert from radians to degrees: degrees = radians * 180 /
Convert from degree to radian: radians = degrees * / 180
【Calculate the distance between two points】
Pythagorean theorem: c2 = a2 + b2
Assume that there are two video clips mc1 and mc2, then the distance c between their two points is:
var c:Number = (( - , 2) + ( - , 2));
【Simulate circular motion】
Knowing the center o(x0, y0), radian r and radian angle, find the coordinates of any point P(x, y) on the circle:
x = x0 + ((angle) * r);
y = y0 + ((angle) * r);
Note: The x-axis positive direction of the stage is horizontally right, and the y-axis positive direction is vertically down.
【Simulated elliptical motion】
Knowing the center o(x0, y0), the major axis a, the minor axis b and the radian angle, find the coordinates of any point P(x, y) on the circle:
x = x0 + ((angle) * a);
y = y0 + ((angle) * b);
【Conversion between Fahrenheit and Celsius】
Fahrenheit temperature = degrees Celsius * 9 / 5 + 32
Celsius temperature = (Fahrenheit - 32) * 5 /9
【Conversion between kilograms and pounds】
kg = pounds * 2.2
lbs = kg / 2.2
【Add elements to the end of the array】
var array:Array = new Array();
("a", "b");
//Add a single element to the end of the array can also be added like this:
array[] = "c";
//If the element set by the index does not exist, the array itself will automatically expand to contain sufficient number of elements. The elements in the middle will be set to undefined:
array[5] = "e";
trace(array[4]); //Output: undefined
【Add elements to the beginning of the array】
var array:Array = ["a", "b"];
("c", "d");
trace(array); //Output: c,d,a,b
[Delete the first element in the array and return the element, use the shift() method]
var letters:Array = new Array("a", "b", "c");
var firstLetter:String = ();
trace(letters); //Output: b,c
trace(firstLetter); //Output: a
[Delete the last element in the array and return the value of the element, use the pop() method]
var letters:Array = new Array("a", "b", "c");
trace(letters); //Output: a,b,c
var letter:String = ();
trace(letters); //Output: a,b
trace(letter); //Output: c
[Delete elements in the array, add new elements to the array and return deleted elements, use the splice() method]
splice(startIndex:int, deleteCount:uint, ... values):Array
startIndex: An integer that specifies the index of the element in the array at the location where the insertion or deletion begins;
deleteCount: An integer that specifies the number of elements to be deleted;
... values: An optional list or array of commas separated by a comma, which is inserted into this array at the location specified by the startIndex parameter.
【Find the first matching element in the array】
var array:Array = ["a", "b", "c", "d", "a", "b", "c", "d"];
var match:String = "b";
for(var i:int = 0; i < ; i++) {
if(array[i] == match) {
trace("Element with index " + i + " found to match " + match);
//Output: Element with index 1 found to match b
break;
}
}
【Find the last matching element in the array】
var array:Array = ["a", "b", "c", "d", "a", "b", "c", "d"];
var match:String = "b";
for(var i:int = - 1; i >= 0; i--) {
if(array[i] == match) {
trace("Element with index " + i + " found to match " + match);
//Output: Element with index 5 found to match b
break;
}
}
【Convert strings into arrays】
Use the() method:
var list:String = "I am YoungBoy.";
var words:Array = (" "); //Slice the string with spaces as delimiter
trace(words); //Output: I,am, YoungBoy.
【Convert array into string】
Use the() method:
var myArr:Array = new Array("one", "two", "three");
var myStr:String = (" and ");
trace(myArr); //Output: one, two, three
trace(myStr); //Output: one and two and three
【Using object arrays to process related data】
var cars:Array = new Array();
({make:"Mike", year:1997, color:"blue"});
({make:"Kelly", year:1986, color:"red"});
for(var i:int = 0; i < ; i++) {
trace(cars[i].make + " - " + cars[i].year + " - " + cars[i].color);
}
//Output:
// Mike - 1997 - blue
// Kelly - 1986 - red
【Get the minimum or maximum value in the array】
var scores:Array = [10, 4, 15, 8];
();
trace("Minimum: " + scores[0]);
trace("Maximum: " + scores[ - 1]);
【Use the for ... in statement to read the associative array elements】
var myObject:Object = new Object();
= "YoungBoy";
= 20;
for(var i:String in myObject) {
trace(i + ": " + myObject[i]);
}
//Output: name: YoungBoy
// age: 20
Note: The for ... in loop will not display all built-in properties of the object. For example, the loop will display special properties that are newly added during execution, but methods of built-in objects will not be listed, even if they are stored in the object properties.
【AVM (ActionScript Virtual Machine) and Rendering Engine
The AVM is responsible for executing ActionScript programs, while the rendering engine draws objects on the display.
【Indicate how many display objects are in the display list of the container】
Each container has a numChildren property.
【Add items to display list】
addChild(child:DisplayObject)
addChildAt(child:DisplayObject, index:int)
index: Adds the index position of the child. If you specify the index position currently occupied, the position and all the child objects on higher positions will be moved up one position in the child list.
【Remove items from the display list】
removeChild(child:DisplayObject)
removeChildAt(index:int)
index: The child index of the DisplayObject to be deleted, and the index position of any display object above the child is subtracted by 1.
If you want to remove all sub-components in the window, you can combine removeChildAt(), numChildren attributes and for loops. Because each time a sub-component is removed, the index position will change, so there are two ways to handle the removal of all sub-components:
1. Always remove sub-components at position 0;
2. Remove the sub-component in reverse, that is, starting from the tail end.
[Change the position of existing children in the display object container]
setChildIndex(child:DisplayObject, index:int):void
Possible methods:
Returns the index position of the child instance of DisplayObject: getChildIndex(child:DisplayObject):int
Returns the instance of the child display object located at the specified index: getChildAt(index:int):DisplayObject
Note: When a sub-element moves to an index lower than its current location, then all sub-elements from the target index to the index before the sub-element index will increase its index by 1, and the sub-element will be assigned to the target index. When the sub-element moves to a higher index, all sub-elements will be caused to the index down to the target index, and all sub-elements will be specified to the target index value.
[Tips about TextField's vertical way to place text at the center point of the button surface]
= (_height - ) / 2;
-= 2; //Subtract 2 pixels to adjust the offset
【External.swf video loading and interaction】
1. Listen to init events;
2. Access the loaded video through the content attribute.
When the loaded video has sufficient initialization work to allow its methods and properties to interact, the init event will be initiated. Only after the loader initiates the init event can the video be controlled. Trying to interact with the loaded video before it is initialized will result in an error during execution.
_loader.(, handleInit); //When the properties and methods of loaded .swf are available
_loader.load(new URLRequest(""));
private function handleInit(event:Event):void {
var movie:* = _loader.content;
trace(());
(0xFF0000);
}
[TextField has two types: dynamic (dynamic) and input (input), the default value is dynamic. Change the TextField type method]
= ; //The default value of the selectable attribute is true
and
【Filter text input】
= "This is inputable";
= "^This is content that is prohibited from entering";
The restrict property supports some styles similar to regular expressions:
= "a-zA-z"; //Only size letters are allowed
= "a-zA-z "; //Only letters and spaces are allowed
= "0-9"; // Only numbers are allowed
= "^abcdefg"; // Except for the lowercase letter abcdefg that is not allowed, everything else is allowed
= "^a-z"; //All lowercase letters are not allowed, but other contents are allowed, including capital letters
= "0-9^5"; //Only numbers are allowed, but 5 exceptions
Let the restrict character contain letters with special meanings (such as - and ^):
= "0-9\\-"; //Available numbers and dash
= "0-9\\^"; //Allow numbers and ^
= "0-9\\\\"; //Allow numbers and backslashes
You can also use Unicode to escape sequences to specify allowed content. For example:
= "^\u001A";
Note: ActionScript is case sensitive. If the restrict property is set to abc, the uppercase form of letters (A, B and C) will become lowercase form (a, b and c) when inputting, and vice versa. The restrict property only affects what the user can enter, and the script can put any text into the text field.
【Set the maximum length of the input box】
:int
【Add content to TextField】
(text:String):void
This method is more efficient than concatenating two strings by using addition assignments to the text attribute (for example += moreText).
【Show HTML text】
= "<b>Html text</b>";
The supported HTML tag sets are: <b>,<i>,<u>,<font> (with face, size and color attributes), < p>,<br>,<a>,<li>,<img> and <textformat> (with leftmargin, rightmargin, blockindent, indent, leading and tabstops attributes, corresponding to the same name attribute of the TextFormat class)
【Reduce the blanks】
= true;
Remove extra whitespace (spaces, line breaks, etc.) in text fields with HTML text, as most HTML browsers do.
Note: Set the condenseWhite property before setting the htmlText property
【Automatic resizing and alignment】
= ;
Optional values:




【Indicates whether the text field will be automatically wrapped】
= true; //Automatic wrap
【Scroll text with program means】
The horizontal direction is in units of pixels, and the vertical direction is in units of rows:
scrollV: indicates the top row of the visible area of ​​the text box, which can be read and written;
bottomScrollV: indicates that the bottom line in the text box is visible and read-only;
maxScrollV: the maximum value of scrollV, read-only;
numLines: Defines the number of text lines in a multi-line text field, read-only;
= ; //Scroll to the last page
【Respond to scroll events】
(, onTextScroll);
[Methods to style text]
1. Use HTML tags to style;
2. Use TextFormat object;
3. Use CSS.
For example: HTML uses <font> tags, TextFormat object sets font attributes, and CSS uses font-family attributes.
Supported Cascading Style Sheet (CSS) attributes and values, and their corresponding ActionScript attribute names (in parentheses):
color(color),display(display),font-family(fontFamily),font-size(fontSize),font-style(fontStyle),font-weight(fontWeight),kerning(kerning),leading(leading),letter-spacing(letterSpacing),margin-left(marginLeft),margin-right(marginRight),text-align(textAlign),text-decoration(textDecoration),text-indent(textIndent)
Supported HTML entities: <(less than sign: <), >(greater than sign: >), &(and: &), "(double quotes: "), '(apostrophe, single quotes: ')
There are two ways to write style objects:
Writing method one:
var sampleStyle:Object = new Object();
= "#FFFFFF";
= "center";
(".sample", sampleStyle);
Writing method two:
var sampleStyle:Object = {color: "#FFFFFF", textAlign: "center"};
(".sample", sampleStyle);
【Style the text entered by the user】
Using the defaultTextFormat property, the style is applied to the text that the user typed in the input box:
var formatter:TextFormat = new TextFormat();
= 0x0000FF; //Turn the text into blue
= formatter;
【Style part of existing text】
(format:TextFormat, beginIndex:int = -1, endIndex:int = -1):void
【Set the font of the text box】
example:
HTML: = "<font face='Arial'>Formatted text</font>";
TextFormat: = "Arial";
CSS: P{ font-family: Arial; }
You can also use comma-separated font lists: = "Arial, Verdana, Helvetica";
Notice:
Fonts and font groups are different. There are three types of font groups: _sans, _serif and _typewriter.
_sans group generally refers to fonts such as Arial or Helvetica;
_serif groups generally refer to fonts such as Times or Times New Roman;
_typewriter groups generally refer to fonts such as Courier or Courier New.
【Embed font】
Use [Embed] to set the tag. [Embed] to set the tag should appear in the ActionScript file and be outside the class declaration. You can embed TrueType font or system font. The syntax when embed TrueType font:
[Embed(source="pathToTtfFile", fontName="FontName", mimeType="application/x-font-truetype")]
pathToTtfFile: The path of the ttf file, and the path of the TrueType font can be relative or absolute;
FontName: Font name;
Syntax of embedded system fonts:
[Embed(systemFont="Times New Roman", fontName="Times New Roman", mimeType="application/x-font-truetype")]
fontName: Take the same name as the actual system font name.
Note: When using embedded fonts, set the embedFonts property of TextField to true, so that TextField can only use embedded fonts. If you try to use device fonts for TextField with embeddedFonts set to true, nothing will be displayed. If embedFonts is set to true, you cannot specify a comma-separated font list.
【Create a rotatable text】
Use inline fonts. When you rotate the text box, the device font will disappear.
【Show Unicode text】
1. Load Unicode text from external sources;
2. If your editor supports Unicode (such as Flex Builder), you can use this character directly in the ActionScript program;
3. Use Unicode escape characters. All Unicode escape characters in ActionScript start with \u, followed by four hexadecimal numbers.
Note: If you want to get Unicode characters, use it under Windows: Start > All Programs > Attachments > System Tools > Character Mapping Table.
【Bring the focus of Flash Player to the text box】
= field;
Remove focus:
= null;
Note: When the .swf file is first loaded into a web browser, there is no focus. Therefore, before assigning the focus to an element of the Flash application in the form of a program, the focus must be moved to Flash Player.
【Select text with ActionScript】
Use (beginIndex:int, endIndex:int):void
In order to select text normally, the text box must have focus:
= field; //Set the focus to the text box
= "This is example text"; //Set text
(0, 4); // Highlight the word "This"
Use the read-only selectionBeginIndex and selectionEndIndex properties to access the index of the selected character range.
[Set the insertion point (cursor position) in the text and access the index value of the cursor position]
You can use () to set the index parameters at the beginning and end to the same value, and set the cursor position in the text (assuming that there is focus):
(0, 0); //Place the insertion point in front of the first character
trace(); //Output index value of cursor position
[Respond when the text field is selected or unselected]
When you get focus: FocusEvent.FOCUS_IN
When the focus is lost: FocusEvent.FOCUS_OUT
When removing focus via the keyboard (Tab key): FocusEvent.KEY_FOCUS_CHANGE
When removing focus through the mouse: FocusEvent.MOUSE_FOCUS_CHANGE
The FocusEvent class has a relatedObject property. As for the FOCUS_IN event, the relatedObject property is the reference address of the object that just had the focus; for the FOCUS_OUT, KEY_FOCUS_CHANGE and MOUSE_FOCUS_CHANGE events, the relatedObject property is the reference address of the object that just received the focus.
Both FOCUS_IN and FOCUS_OUT events occur after the focus changes, so both are non-cancellable events. For the KEY_FOCUS_CHANGE and MOUSE_FOCUS_CHANGE events, the default behavior can be cancelled using the () method:
(FocusEvent.KEY_FOCUS_CHANGE, onKeyFocus);
private function onKeyFocus(event:FocusEvent):void {
if( == "") {
(); //Until the field has no text, the Tab key is not allowed to remove the focus
}
//It is the reference address of the object that has the focus just now, that is, the reference address of the next object that has the focus.
}