Putting it together · Menggabungkannya
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.
Menggabungkannya
- Program nyata menggabungkan variabel, perulangan, fungsi, array, dan objek.
- Perulangan
for...ofmembaca setiap item array secara langsung — tidak perlu indeks.
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 membangun total
for...of reads each item directly. Watch t add them up, one at a time. · for...of membaca setiap item secara langsung. Perhatikan t menambahkannya, satu demi satu.
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
Pencarian dan Penghitungan
- Loop melalui array, dan simpan penghitung (atau penanda) saat berjalan.
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.
Kesalahan umum
- Bangun langkah demi langkah dan gunakan
console.loguntuk memeriksa sepanjang proses. - Pertahankan HTML, CSS, dan JavaScript melakukan tugas mereka masing-masing.
Now you try
- Write each function using a loop.
- Press Check answer to test it.
Sekarang Anda coba
- Tulislah setiap fungsi menggunakan perulangan.
- Tekan Cek jawaban untuk mengujinya.
Write a function total(nums) that returns the sum of every number in the array nums. · Tulis fungsi total(nums) yang mengembalikan jumlah setiap angka dalam array nums.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Write a function biggest(nums) that returns the largest value in the array. · Tulis fungsi biggest(nums) yang mengembalikan nilai terbesar dalam array.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit. · Tulis fungsi countAbove(nums, limit) yang mengembalikan berapa banyak angka yang lebih besar dari limit.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.