Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Mastering JavaScript Arrays Sum-Up | Mastering JavaScript Arrays
JavaScript Data Structures

book
Mastering JavaScript Arrays Sum-Up

Arrays are data structures used to store and manipulate collections of values.

Creating Arrays

  • Arrays in JavaScript are created using square brackets [] and are known as array literals;

  • Commas separate elements within the array.

js
// Array literal creation
const colors = ["red", "green", "blue"];
const numbers = [1, 2, 3, 4, 5];

// Arrays with different data types
const mixedArray = ["apple", 42, true, { name: "John" }];

Accessing Array Elements

  • 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;

  • Specific elements within an array can be accessed by using square brackets with the element's index.

js
const firstColor = colors[0]; // "red"
const secondNumber = numbers[1]; // 2

Modifying Array Elements

Array elements can be changed by accessing them through their index and assigning a new value.

js
colors[1] = "yellow";
numbers[0] = 10;

Array Length

The length property of an array represents the number of elements it contains. It automatically adjusts when elements are added or removed.

js
const colorsCount = colors.length; // 3
const numbersCount = numbers.length; // 5

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, which is array.length - 1.

js
const lastColor = colors[colors.length - 1];
const lastNumber = numbers[numbers.length - 1];

For Loop

  • The for loop is used for iterating over an array element by element;

  • It uses a loop counter variable (e.g., i) to access each element by index;

  • The loop continues as long as the counter is less than the array's length;

  • It's a fundamental tool for array iteration.

js
for (let i = 0; i < numbers.length; i+=1) {
console.log(numbers[i]);
}

For...of Loop

  • The for...of loop is a more modern and concise way to iterate over arrays;

  • It automatically handles the loop counter and provides direct access to each element's value;

  • It simplifies array iteration, making the code cleaner and more readable.

js
for (const color of colors) {
console.log(color);
}
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 9

Pergunte à IA

expand
ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

some-alt