This section provides a quick description and a tutorial example script on the 'Array' built-in object type, which is used to create arrays.
The "Array" object type is a special built-in object type to be used to create new arrays.
It has the following main features:
New arrays can be created with the "Array()" constructor.
All "Array" objects have an inherited property called "length" representing the number of elements of the array.
All "Array" objects have many inherited methods: reverse(), sort(), indexOf(), push(), pop(), shift(), etc..
All elements in an array are actually properties with their indexes as property names.
A "Array" object can also be created with an array literal: [elements...].
A "Array" object can also be created with the Array function: Array(elements...).
Here is a tutorial example script showing some of the those features:
// Array_Object_Type.html
// Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
// Creating a new array
var colors = new Array("Red", "Green", "Blue");
// Checking this object
println("\nAbout this \"colors\":");
println(" Type = "+(typeof colors));
println(" Instance Of Object: "+(colors instanceof Object));
println(" Instance Of Array: "+(colors instanceof Array));
println("\nList of array properties:");
for (item in colors) {
println(" "+item+" = "+colors[item]);
}
// Using array's inherited property and method
colors.push("Yellow");
colors.sort();
// Accessing elements through indexes
println("\nAfter push() and sort():");
for (var i=0; i<colors.length; i++) {
println(" "+i+" = "+colors[i]);
}
If you run this script with "jrunscript", you will get:
About this "colors":
Type = object
Instance Of Object: true
Instance Of Array: true
List of array properties:
0 = Red
1 = Green
2 = Blue
After push() and sort():
0 = Blue
1 = Green
2 = Red
3 = Yellow
Now we know how to create arrays with the "Array()" constructor.
Read other "Array" related chapters to see more tutorial examples.