JS-JavaScript array

xiaoxiao2021-03-06  58

In JavaScript 1.0, there are only Date objects and user-defined objects. You may expect a group constructor, but have not been implemented until JavaScript 1.1 appears, your expectation has become a reality. We can define user objects as follows:

Function blankArray (n) {

For (VAR i = 0; i

THIS [I] = NULL;

THIS.LENGTH = N;

}

The BlankArray function created an array that there is n blank items in this array. An example of using this constructor is given below:

Var myarray = new blankArray (3);

MyArray [0] = "Hello";

MyArray [1] = "world";

MyArray [2] = "!";

If you have some experience in other programming languages ​​(such as C language), you will until the index of the array is starting 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 'Arguments' attributes to assign values ​​to array instead of creating an empty array element, this property is existing for all functions. Although there is no given any parameters, the transmitted value can still be accessed through the Arguments array. The specific code is as follows:

Function MakeArray () {

For (var i = 0; i

THIS [I] = arguments [i];

THIS.LENGTH = arguments.length;

}

The call to the constructor can be like this:

Var myArray = new MakeArray ("Hello", "World", "!");

In JavaScript 1.1, creating an array constructor combines the specifics of BlankArray and MakeArray. One of the following calls:

Var myarray = new array (3); // Requires JS 1.1

This call creates a blank array (which is 3) as a BlankArray constructor above. In Netscape, it is called 'Dense Array', because each element has a value, can be created as follows:

Var myArray = new array (value1, value2, value3); // JS 1.1 Since you are familiar with the constructor and object properties, we can further give some examples. If you are using JavaScript 1.1 or higher, you can use an array constructor. Otherwise you use the MakeArray object more appropriate. Var Workpeople = New Array

New Person ("Thomas", 25, "Green"),

New Person ("Richard", 35, "Blue",

New Person ("Harold", 30, "Chartreuse")

);

Workpeople is an array with three Person objects. Every Person has Name (name), aged (age), color (skin color), and BIRTHYEAR (birth year) attribute.

An example is given below to use us. Here you still have to remind, the Person code block and the WorkPeople array must include the same Script tag or elsewhere in the web page.