In JavaScript1.0, the constructor only contains the Date object and user-defined object. You may expect an array constructor, but it never works until JavaScript1.1 appears. Your expectation becomes a reality. For example, we can define a user object: functionblankArray (n) {for (vari0; in; I ++) this [I] null; t
In JavaScript1.0, the constructor only contains the Date object and user-defined object. You may expect an array constructor, but it never works until JavaScript1.1 appears. Your expectation becomes a reality. We can define user objects as follows:
Function blankArray (n ){
For (var I = 0; I <n; I ++)
This [I] = null;
This. length = n;
}
The blankArray function creates an array with n blank items. The following example uses the constructor:
Var myArray = new blankArray (3 );
MyArray [0] = "hello ";
MyArray [1] = "world ";
MyArray [2] = "! ";
If you have some experience with other programming languages (such as C), you will continue until the array index starts from 0 rather than from 1. Therefore, in the above example, the array index is from 0 to 2, so the length of this array is 3.
The following code is a more advanced array constructor. It uses the 'arguments' attribute to assign values to the array, instead of creating an empty array element. This attribute exists for all functions. Although no parameters are given, the passed values can still be accessed through the arguments array. Details
Function makeArray (){
For (var I = 0; I <arguments. length; I ++)
This [I] = arguments [I];
This. length = arguments. length;
}
The constructor call can be as follows:
Var myArray = new makeArray ("hello", "world ","! ");
In JavaScript 1.1, the array constructor is used to create an array constructor that combines the specific parameters of blamkarray and makeArray. The following is a call:
Var myArray = new Array (3); // requires JS 1.1
This call creates a blank array (with a length of 3) as the blamkarray constructor demonstrated above. In Netscape, it is called 'densearray', because each element has a value, which can be created as follows:
Var myArray = new Array (value1, value2, value3); // JS 1.1
Since you are familiar with the constructor and object attributes, we can give some further examples. If you are using JavaScript1.1 or later, you can use the array constructor. Otherwise, it is more appropriate to use the makeArray object. Var workPeople = newArray (
New Person ("Thomas", 25, "green "),
New Person ("Richard", 35, "blue "),
New Person ("Harold", 30, "chartreuse ")
);
WorkPeople is an array with three Person objects. Each Person has attributes such as name, age, color, and birthYear.
Here is an example to use what we learned above. Note that the Person code block and The workPeople array must be included in the same SCRIPT tag or somewhere else on the webpage.