Перейти к основному содержимому
Frontend — это бесплатный бонус CodeMentor AI; основной продукт — Python. Зарегистрируйся, чтобы сохранить прогресс и открыть все 299 уроков фронтенда + 1,100+ уроков Python.Зарегистрироваться — бесплатно
← ⚡ JavaScript & the browser·Модуль C1 · Урок 9
ЗаданиеGiven const fruits = ['apple', 'banana', 'cherry']: use for-of to log each fruit on its own line; then use forEach to log 'index: fruit' (e.g. '0: apple') for each.

Циклы: for-of, forEach и когда какой использовать.

75 XP7 minFREE
Теория

Three modern ways to iterate

const items = ["a", "b", "c"];

// for-of: cleanest when you want each value
for (const item of items) {
  console.log(item);
}

// .forEach: same idea, method-call style
items.forEach((item, index) => {
  console.log(index, item);
});

// classic for: only when you need an index AND control over flow
for (let i = 0; i < items.length; i += 1) {
  console.log(i, items[i]);
}

When each one fits

NeedUse
Each value, no indexfor-of
Each value + index.forEach
Step by 2, or break, or index mathclassic for
Build a new array.map (covered in C1-04)
Reduce to a single value.reduce

The break gotcha

items.forEach((item) => {
  if (item === "b") return;   // 'return' skips THIS iteration, not the loop
});

for (const item of items) {
  if (item === "b") break;    // actually exits the loop
}

forEach has no break. If you need to stop mid-iteration, use for-of (or some / find for searches). The first time you reach for break inside a forEach, you've outgrown it.

Don't reach for vanilla for unless you must

In code review, a plain for (let i = ...) is now a yellow flag — there's almost always a more expressive choice. Keep it for cases where the index does the heavy lifting (matrix walks, sliding windows, step != 1).

2 вкладок
Живой просмотр
console output appears here…
← НазадСледующий урок →

Получай один совет по Python или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.