Summary of “Arrays”. Part 1
An array is a data type that is a list of elements, each of which has its own sequence number.
In the array you can store any data: strings, Boolean values, numbers and even other arrays.
Numbering of array elements starts from zero, therefore the sequence number (index) of the first element equals zero.
You can use a variable as an index.
Use the [].length
command to calculate array length (how many elements it has). You can use it to get the last element of the array.
var numbers = [1, 2, 3, 4, 5];
var index = 3;
// Will log 1 in the console
console.log(numbers[0]);
// Will log 4 in the console
console.log(numbers[index]);
// Will log 5 in the console
console.log(numbers.length);
// Will log 5 in the console
console.log(numbers[numbers.length - 1]);
Arrays can be sorted in loops. For example, the loop below logs array elements in the console one by one and stops working when i
becomes equal to the length of the array.
var numbers = [1, 2, 3, 4, 5];
for (var i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// Will log 1
// Will log 2
// Will log 3
// Will log 4
// Will log 5
Writing to an array is done in the same way as reading: by using square brackets.
var numbers = [];
var index = 1;
numbers[0] = 1;
numbers[index] = 2;
// Will log [1,2] in the console
console.log(numbers);
Continue