Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Робота з Масивами за Допомогою `push`, `pop` | Section
Основи JavaScript

bookРобота з Масивами за Допомогою `push`, `pop`

Свайпніть щоб показати меню

push()

The push method adds one or more elements to the end of an array and returns the new length. For example:

12345
const numbers = [1, 2, 3]; console.log("Before:", numbers); numbers.push(4); // numbers is now [1, 2, 3, 4] console.log("After:", numbers); console.log(numbers.length); // 4
copy

pop()

The pop method removes the last element from an array and returns it. The array's length decreases by one:

12345
const numbers = [1, 2, 3, 4]; console.log("Before:", numbers); const lastNumber = numbers.pop(); // lastNumber is 4, numbers is now [1, 2, 3] console.log("After:", numbers); console.log(numbers.length); // 3
copy

The push and pop methods are essential for handling dynamic data in real-world applications. These methods let you add and remove items from arrays as your data changes.

Adding Messages to a Chat

When a user sends a new message, use push to add it to the end of the chat history array:

123
const chatHistory = ["Hello!", "How are you?"]; chatHistory.push("I'm good, thanks!"); console.log(chatHistory);
copy

Undoing the Latest Action

If you want to let users undo their last action, use pop to remove and retrieve the most recent entry from an array:

1234
const actions = ["draw line", "erase", "add text"]; const lastAction = actions.pop(); console.log(lastAction); // Output: "add text" console.log(actions); // Output: ["draw line", "erase"]
copy

These methods help you manage lists that change as users interact with your application, such as updating shopping carts, tracking steps in a game, or managing recent edits. By using push and pop, you can keep your data organized and responsive to user actions.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 12

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 12
some-alt