Массивы в JavaScript

Содержание
Введение
Преобразовать HTMLCollection в массив
Примеры
Длина массива
forEach(): перебор элементов массива
Похожие статьи

Введение

HTMLCollection

HTMLCollection это не массив. Если к ней применить метод forEach получится ошибка

Uncaught TypeError: htmlcollection.forEach is not a function

Преобразовать HTMLCollection в array можно несколькими способами

Array.from(HTMLCollection) [].slice.call(HTMLCollection) [...HTMLCollection]

Примеры

Разными способами создадим массивы из элементов у которых есть класс A, B и C

const arrA = Array.from(document.getElementsByClassName("A")); const arrB = [].slice.call(document.getElementsByClassName("B")); const arrC = [...document.getElementsByClassName("C")];

Длина массива

array.length

a = [0, 1, 2]; console.log(a.length);

3

forEach(): перебор элементов массива

Для перебора элементов массива можно использовать функцию forEach()

Чтобы сделать все элементы массива arr невидимыми:

arr.forEach(function(item, index) { item.style.display = "none"; });

Спрятать все баннеры кроме одного

Если нужно показывать баннеры по очереди

const getRandomInt = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive }; function hideAllButOne(arr, previous, timeout) { let randInt = getRandomInt(0, arr.length); if (previous !== -1 && previous !== randInt) { arr[randInt].style.display = "inline"; arr[previous].style.display = "none"; } else if (previous === -1) { arr.forEach(function(item, index) { item.style.display = "none"; }); arr[randInt].style.display = "inline"; } let t = setTimeout(hideAllButOne, timeout, arr, randInt, timeout); } const elements1 = Array.from(document.getElementsByClassName("firstAdvBlock")); const elements2 = [].slice.call(document.getElementsByClassName("BlinkingBanner")); setTimeout(hideAllButOne, 1000, elements1, -1, 36000); setTimeout(hideAllButOne, 1000, elements2, -1, 18000);

Article author: Andrei Olegovich

Похожие статьи
JavaScript
Функции
typeof(): Определить тип переменной
Массивы
Сортировка массива
Скролл вверх и вниз
Определить ширину экрана
Mocha Framework
Запросы к REST API на JS
TicTacToe
Ошибки

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: