|
Arrays
An Array is a map from integers to values. In JavaScript, all objects can map from integers to values, but Arrays are a special type of object that has extra behavior and methods specializing in integer indices (e.g., join, slice, and push).
Arrays have a length property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated if one creates a property with an even larger index. Writing a smaller number to the length property will remove larger indices. This length property is the only special feature of Arrays that distinguishes it from other objects.
Elements of Arrays may be accessed using normal object property access notation:
myArray[1]
myArray["1"]
These two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number:
myArray.1 (syntax error)
myArray["01"] (not the same as myArray[1])
Declaration of an array can use either an Array literal or the Array constructor:
myArray = [0,1,,,4,5]; (array with length 6 and 4 elements)
myArray = new Array(0,1,2,3,4,5); (array with length 6 and 6 elements)
myArray = new Array(365); (an empty array with length 365)
Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". Setting myArray[10] = 'someThing' and myArray[57] = 'somethingOther' only uses space for these two elements, just like any other object. The length of the array will still be reported as 58.
Object literals allow one to define generic structured data:
var myStructure = {
name: {
first: "Mel",
last: "Smith"
},
age: 33,
hobbies: [ "chess", "jogging" ]
};
|