04. Array Iteration

for-in loop

Цикл for..in перебирает все определенные индексы массива:

const colors = ["red", "green", "blue"];
for (const index in colors) {
  console.log(colors[index]);
}

for loop

Обыкновенный цикл for:

const colors = ["red", "green", "blue"];
for (const i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

forEach function

Цикл forEach применяет функцию к каждому элементу массива. Дыры в массиве игнорируются (за исключением, если они были присвоены явно):

const colors = ["red", "green", "blue"];
colors.forEach((item, index, array) => {
  console.log(item, index);
});

for..of loop

Цикл for..of неявно создает итератор и перебирает каждый элемент массива (ES6):

const colors = ["red", "green", "blue"];
for (const color of colors) {
  console.log(color);
}

arr.entries()

Функция entries возвращает массив пар индекс-значение:

const arr = ["a", "b", "c"];
const eArr = arr.entries();

console.log(eArr.next().value); // [0, 'a']
console.log(eArr.next().value); // [1, 'b']
console.log(eArr.next().value); // [2, 'c']

arr.values()

Функция values --- возвращает итератор по всем значениям в массиве. Удобно использовать в for..of цикле.

const arr = ["w", "y", "k", "o", "p"];
const eArr = arr.values();
for (const letter of eArr) {
  console.log(letter);
}

arr.keys()

Функция keys --- возвращает итератор по всем ключам-индексам в массиве.

const arr = ["a", "b", "c"];
const iterator = arr.keys();

Last updated