Putting it together · Объединение всего вместе
Putting it together
- Real programs combine variables, loops, functions, arrays and objects.
- A
for...ofloop reads each item of an array directly — no index needed.
Собираем всё вместе
- Реальные программы сочетают переменные, циклы, функции, массивы и объекты.
- Цикл
for...ofчитает каждый элемент массива непосредственно — индекс не нужен.
function total(nums) {
let t = 0;
for (const n of nums) {
t = t + n;
}
return t;
}
console.log(total([4, 8, 6])); // → 18
for...of builds the total · Цикл for...of накапливает сумму
for...of reads each item directly. Watch t add them up, one at a time. · for...of читает каждый элемент напрямую. Следите за тем, как t суммирует их по одному.
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
Поиск и подсчёт
- Проходите по массиву и ведите счетчик (или флаг) по ходу выполнения.
function countAbove(nums, limit) {
let count = 0;
for (const n of nums) {
if (n > limit) {
count++;
}
}
return count;
}
console.log(countAbove([3, 7, 2, 8], 4)); // → 2
Common mistakes
- Build in small steps and use
console.logto check as you go. - Keep the HTML, CSS and JavaScript doing their own jobs.
Распространенные ошибки
- Стройте решение небольшими шагами и используйте
console.logдля проверки на каждом этапе. - Держите HTML, CSS и JavaScript各自 выполняющими свои задачи.
Now you try
- Write each function using a loop.
- Press Check answer to test it.
Теперь попробуйте сами
- Напишите каждую функцию с использованием цикла.
- Нажмите Проверить ответ, чтобы протестировать её.
Write a function total(nums) that returns the sum of every number in the array nums. · Напишите функцию total(nums), которая возвращает сумму всех чисел в массиве nums.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Write a function biggest(nums) that returns the largest value in the array. · Напишите функцию biggest(nums), которая возвращает наибольшее значение в массиве.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit. · Напишите функцию countAbove(nums, limit), которая возвращает количество чисел, больших, чем limit.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.