Flash / Flex / ActionScript/Array/length
Содержание
- 1 Access the last element of theArray: theArray[theArray.length - 1]
- 2 Determining the Size of an Array
- 3 Putting an element at index Array .length creates a new element right after the current last element
- 4 Removing Elements with the length Variable
- 5 The length property of an array returns the number of elements in the array.
- 6 Use the Array constructor allows you to specify the length of the new array.
Access the last element of theArray: theArray[theArray.length - 1]
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var cities:Array = ["Toronto", "Montreal", "Vancouver", "Waterloo"];
trace(cities); // Toronto,Montreal,Vancouver,Waterloo
}
}
}
Determining the Size of an Array
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var list:Array = [34, 45, 57];
trace(list.length); // Displays: 3
var words:Array = ["this", "that", "the other"];
trace(words.length); // Displays: 3
var cards:Array = new Array(24);
trace(cards.length); // Displays: 24
}
}
}
Putting an element at index Array .length creates a new element right after the current last element
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var array:Array = new Array();
array.push("val 1", "val 2");
array[array.length] = "val 3";
trace(array);
}
}
}
Removing Elements with the length Variable
To delete elements from the end of the array: set the array"s length variable to a number smaller than the current length:
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var toppings:Array = ["p", "t", "c", "g", "b"];
toppings.length = 3;
trace(toppings); //p,t,c
}
}
}
The length property of an array returns the number of elements in the array.
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var aEmployees:Array = ["A", "P", "C", "H"];
for(var i:Number = 0; i < aEmployees.length; i++) {
trace(aEmployees[i]);
}
}
}
}
Use the Array constructor allows you to specify the length of the new array.
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var topTen:Array = new Array(10);
// creates an array with 10 spaces.
trace(topTen.length);
}
}
}