Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1. Вывод элементов в консоль
- const fruits = ['яблоко', 'банан', 'вишня'];
- fruits.forEach(function(item, index) {
- console.log(`${index}: ${item}`);
- });
- // 2. Сумма чисел
- const numbers = [1, 2, 3, 4, 5];
- let sum = 0;
- numbers.forEach(function(n) {
- sum += n;
- });
- console.log(sum); // 15
- // 3. Изменение DOM‑элементов
- // (предполагаем, что в HTML есть <ul id="list"><li>…</li>…</ul>)
- const items = document.querySelectorAll('#list li');
- items.forEach(function(li, i) {
- li.textContent = `Пункт ${i + 1}: ${li.textContent}`;
- li.style.color = i % 2 === 0 ? 'blue' : 'green';
- });
- // 4. Перебор двумерного массива
- const matrix = [
- [1, 2],
- [3, 4],
- [5, 6]
- ];
- matrix.forEach(function(row, rowIndex) {
- row.forEach(function(value, colIndex) {
- console.log(`matrix[${rowIndex}][${colIndex}] = ${value}`);
- });
- });
- // 5. Создание нового массива «вручную»
- const original = ['a', 'b', 'c'];
- const uppercased = [];
- original.forEach(function(ch) {
- uppercased.push(ch.toUpperCase());
- });
- console.log(uppercased); // ['A','B','C']
- // 6. Условная обработка
- const data = [10, 15, 20, 25];
- data.forEach(function(n) {
- if (n % 2 === 0) {
- console.log(`${n} — чётное`);
- } else {
- console.log(`${n} — нечётное`);
- }
- });
- // 7. Асинхронные операции
- const urls = ['url1', 'url2', 'url3'];
- urls.forEach(function(url) {
- fetch(url)
- .then(response => response.text())
- .then(text => console.log(`Получили ${text.length} символов с ${url}`))
- .catch(err => console.error(err));
- });
Advertisement
Add Comment
Please, Sign In to add comment