Conteúdo do Curso
JavaScript Data Structures
JavaScript Data Structures
Understanding Arrays
Arrays are versatile data structures used to store and manipulate collections of values. They are commonly used for managing lists of some items. Here, we will explore the creation of arrays and how to access their elements.
Creating Arrays
We can create an array using square brackets []
, known as array literals. Commas should separate elements within the array.
Here, the sport
array contains three elements: "basketball", "hockey", and "cricket".
Accessing Array Elements
We can access specific elements within an array by using square brackets with the element's index. Array indices start at 0, meaning the first element has an index of 0, the second element has an index of 1, and so on.
const motorcycleBrands = ["Harley-Davidson", "Honda", "Kawasaki", "Suzuki"]; console.log(motorcycleBrands[0]); // Output: Harley-Davidson console.log(motorcycleBrands[1]); // Output: Honda console.log(motorcycleBrands[2]); // Output: Kawasaki console.log(motorcycleBrands[3]); // Output: Suzuki
In this example, we access the elements of the motorcycleBrands
array using their indices.
- The first element is accessed with
motorcycleBrands[0]
; - The second with
motorcycleBrands[1]
; - The third with
motorcycleBrands[2]
; - The forth with
motorcycleBrands[3]
.
1. How do we create an array in JavaScript?
2. Which of the following statements correctly defines an array with three elements: "apple," "banana," and "cherry"?
3. What is the index of the first element in an array?
4. In the example below, how can we access the second element ("Laptop"
) of the products
array?
5. What will be the output in the code below?
Obrigado pelo seu feedback!