Arrays in JavaScript
An array is a special type of objectA "bundle" of values. 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 syntaxThe rules for expression.
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 indexThe position of a value in an array or string. or an expression that evaluates to an index value), or an item can be changed or added using the following syntaxThe rules for expression.:
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 propertyA slot for one of the values bundled in an object. 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 consumesUsed to describe a function taking values as inputs. 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"
.