Array indexing and length
Each value in an array has a unique position, called an index.
Indexes start at 0
for the first element (this is called zero indexing). The length of an array can be accessed with the length
property, which allows for a common programming pattern where a for
loop is used to iterate over the elements of an array.
Loading TypeScript...
Notice that the index of the last element of an array is array.length - 1
. For example, if we wanted to extend the program above to calculate any length of the Fibonacci sequence, we could use a while
loop to keep appending new items.
Loading TypeScript...