Array object in JavaScript, reference and interactive test
Before the online test of attributes and methods of the Array object, a description of each.
The Array object was first implemented in JavaScript version 1.1 and has been augmented in version 1.3, that is compatible with the ECMA-262 standard as is the version 1.5 which is described here.
The constructor has two sort of parameters
The constructor supports for argument, either the size of the array, or a list of contained items.
The syntax is:
var x = new Array(number);
ou
var x = new Array(item0, item1, etc...);
Example:
var x = new Array("one", "two", 254);
A variable may be an argument as any object:
var y = "demo";
var x = new Array(y);
document.write(x[0]);
You can also create a array from a literal:
var a = [ "one", "two", 254 ];
The variable declared in a such way will get the attributes and methods of the Array object.
Items are accessed by an index
Arrays, whether created from a literal or a constructor, are objects. Elements can be accessed by the index as explained in the chapter Arrays and JavaScript.
Example:
var x = new Array("one", "two", 254);
document.write(x[2]) // must return 254
Size and regular expression attributes
Array has the following attributes:
int length
The number of elements of the array, or scheduled to be inserted into the array.
Example showing the size given by the attribute length.
var x = new Array(10);
x[2] = "two";
document.write(x);
document.write(x.length);
If the array is created dynamically, length is the number of elements present.
But if we create empty locations, by assigning a position beyond the last useed position, the size takes into account the empty slots.
Example:
var x = new Array();
x[4] = four";
int index
For a array that is the result of the test of a regular expression, is the index of the string found.
String input
For a array that is the result of a test of a regular expression is the initial string on which the test is applied.
Assigning an array creates a new reference
If we assign the array b to the variable a, the two variables a and b will point to the same array.
var b = ["one", "two"]
var a = b
b.push("three")
document.write(a)>
Result:
To make a copy independent of the original, we use the slice method.
var a = b.slice()
Trying interactively methods to access items or transform the array
As with any object, you can invoke methods associated with the name of an instance of Array.
var x = new Array();
x.push("a");
From a set of strings that you give to create the array, you will test methods of this object.
See also
- Multi dimensional array: See the chapter Arrays and JavaScript.
- For each in JavaScript: See the chapter Browsing arrays, for each in JavaScript.
A benchmark is added in the demo.