Putting it together · Tout mettre ensemble
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.
Tout mettre ensemble
- Les vrais programmes combinent variables, boucles, fonctions, tableaux et objets.
- Une boucle
for...oflit chaque élément d'un tableau directement — pas besoin d'index.
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 construit le total
for...of reads each item directly. Watch t add them up, one at a time. · for...of lit chaque élément directement. Observez comment t les additionne, un par un.
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
Chercher et compter
- Bouclez à travers le tableau, et gardez un compteur (ou un indicateur) au passage.
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.
Erreurs courantes
- Construisez par petites étapes et utilisez
console.logpour vérifier au fur et à mesure. - Gardez le HTML, CSS et JavaScript faisant leurs propres tâches.
Now you try
- Write each function using a loop.
- Press Check answer to test it.
À vous maintenant
- Écrivez chaque fonction en utilisant une boucle.
- Appuyez sur Vérifier la réponse pour tester.
Write a function total(nums) that returns the sum of every number in the array nums. · Écrivez une fonction total(nums) qui retourne la somme de tous les nombres du tableau nums.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Write a function biggest(nums) that returns the largest value in the array. · Écrivez une fonction biggest(nums) qui retourne la valeur la plus grande du tableau.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit. · Écrivez une fonction countAbove(nums, limit) qui retourne combien de nombres sont supérieurs à limit.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.