Conteúdo do Curso
JavaScript Data Structures
JavaScript Data Structures
Working with Array Elements
Let's explore how to
- Modify array elements;
- Find the length of an array;
- Access the last element and delve deeper into the concept of indexing.
Modifying Array Elements
Array elements can be changed by accessing them through their index and assigning a new value.
const weekdays = ["Monday", "Tuesday", "Wednesday"]; weekdays[0] = "Lunes"; weekdays[1] = "Martes"; console.log(weekdays); // Output: Lunes, Martes, Wednesday
Here, we modify the first two elements of the weekdays
array to their Spanish translations.
Array Length
The length
property of an array represents the number of elements it contains. This property is dynamic and automatically adjusts when elements are added or removed.
const mountains = ["Everest", "K2", "Kangchenjunga", "Lhotse"]; console.log(mountains.length); // Output: 4
In this example, the mountains
array contains four elements, and mountains.length
returns 4
.
Finding the Last Element
To retrieve the value of the last element in an array, we can calculate its index using the array's length. The index of the last element is always array.length - 1
.
const vehicles = ["car", "bike", "bus", "train"]; const lastIndex = vehicles.length - 1; console.log(vehicles[lastIndex]); // Output: train
In this case, lastIndex
is computed as 3
, which is the index of the last element, and we access the last element using vehicles[lastIndex]
.
Obrigado pelo seu feedback!