Arrays in JavaScript
An array is a special type of object used to store a sequence of items, which means that the result of using the function typeof
on an array will result in the output object
.
Creating a new array
A new array can be created using the syntax
var myArray = [item1, item2, item3];
where for an empty array no items are specified.
Accessing and changing elements
A specific item can be accessed using the syntax myArray[i]
(where i
can be either an index or an expression that evaluates to an index value), or an item can be changed or added using the following syntax:
myArray[1] = newItem;
The first index is 0.
Since any index can be used, there may be "holes" in the array without items. This also means that the property length
may not give the number of items in the array; it instead gives one plus the largest index storing an element.
As an example, after the following steps are executed
var myArray = ["a", "b", "c"];
myArray[12] = ["d"];
the length of myArray
is 13.
Forming an array of strings
An array of strings can be formed from a string using the string method .split(string)
which consumes a string that is used to split the input string into substrings, which then become items in an array. For example:
"a-b-c".split("-");
will result in a list containing the three items "a"
, "b"
, and "c"
.