Массивы в 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);
JavaScript | |
Функции | |
typeof(): Определить тип переменной | |
Массивы | |
Сортировка массива | |
Скролл вверх и вниз | |
Определить ширину экрана | |
Mocha Framework | |
Запросы к REST API на JS | |
TicTacToe | |
Ошибки |