Hasli4

Array. Perebor

Jul 3rd, 2025
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. // 1. Вывод элементов в консоль
  2. const fruits = ['яблоко', 'банан', 'вишня'];
  3. fruits.forEach(function(item, index) {
  4. console.log(`${index}: ${item}`);
  5. });
  6.  
  7. // 2. Сумма чисел
  8. const numbers = [1, 2, 3, 4, 5];
  9. let sum = 0;
  10. numbers.forEach(function(n) {
  11. sum += n;
  12. });
  13. console.log(sum); // 15
  14.  
  15. // 3. Изменение DOM‑элементов
  16. // (предполагаем, что в HTML есть <ul id="list"><li>…</li>…</ul>)
  17. const items = document.querySelectorAll('#list li');
  18. items.forEach(function(li, i) {
  19. li.textContent = `Пункт ${i + 1}: ${li.textContent}`;
  20. li.style.color = i % 2 === 0 ? 'blue' : 'green';
  21. });
  22.  
  23. // 4. Перебор двумерного массива
  24. const matrix = [
  25. [1, 2],
  26. [3, 4],
  27. [5, 6]
  28. ];
  29. matrix.forEach(function(row, rowIndex) {
  30. row.forEach(function(value, colIndex) {
  31. console.log(`matrix[${rowIndex}][${colIndex}] = ${value}`);
  32. });
  33. });
  34.  
  35. // 5. Создание нового массива «вручную»
  36. const original = ['a', 'b', 'c'];
  37. const uppercased = [];
  38. original.forEach(function(ch) {
  39. uppercased.push(ch.toUpperCase());
  40. });
  41. console.log(uppercased); // ['A','B','C']
  42.  
  43. // 6. Условная обработка
  44. const data = [10, 15, 20, 25];
  45. data.forEach(function(n) {
  46. if (n % 2 === 0) {
  47. console.log(`${n} — чётное`);
  48. } else {
  49. console.log(`${n} — нечётное`);
  50. }
  51. });
  52.  
  53. // 7. Асинхронные операции
  54. const urls = ['url1', 'url2', 'url3'];
  55. urls.forEach(function(url) {
  56. fetch(url)
  57. .then(response => response.text())
  58. .then(text => console.log(`Получили ${text.length} символов с ${url}`))
  59. .catch(err => console.error(err));
  60. });
  61.  
Advertisement
Add Comment
Please, Sign In to add comment