Putting it together
Esta página necesita un navegador reciente (con soporte para SharedArrayBuffer). Por favor, actualiza Chrome, Edge, Firefox o Safari a la última versión.
English
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.
English
function longWords(words) {
const result = [];
for (const w of words) {
if (w.length >= 5) {
result.push(w);
}
}
return result;
}
console.log(longWords(["cat", "apple", "sun", "banana"])); // → ["apple", "banana"]
w |
w.length >= 5? |
result after |
|---|---|---|
"cat" |
no | [] |
"apple" |
yes | ["apple"] |
"sun" |
no | ["apple"] |
"banana" |
yes | ["apple", "banana"] |
resultstarts as an empty array before the loop, and the function returns it after the loop.
Explorar
for...of builds the total
for...of reads each item directly. Watch t add them up, one at a time.
English
Searching and counting
- Loop through the array, and keep a counter, a total or a flag as you go.
- A flag starts
falseand becomestrueat the first match. Once you know the answer,returnit straight away.
English
function hasNegative(nums) {
for (const n of nums) {
if (n < 0) {
return true; // found one: stop now
}
}
return false; // only after checking every item
}
console.log(hasNegative([3, -1, 4])); // → true
console.log(hasNegative([2, 5])); // → false
function average(scores) {
let sum = 0;
for (const s of scores) {
sum += s;
}
return sum / scores.length;
}
console.log(average([70, 85, 90])); // → 81.66666666666667
English
Common mistakes
- Build in small steps and use
console.logto check as you go. - Set a running total to
0(or a list to[]) before the loop, not inside it, or it starts again every time round. return falseinside the loop, in anelse, stops after the first item. Returnfalseonly after the loop has checked everything.- For the largest value, start with the first item (
nums[0]), not0: with[-5, -2], starting at0would wrongly give0.
English
Now you try
- Write each function using a loop.
- Press Check answer to test it.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Write a function total(nums) that returns the sum of every number in the array nums.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Write a function biggest(nums) that returns the largest value in the array.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Write a function countAbove(nums, limit) that returns how many numbers are mayor que limit.
Haz clic en Ejecutar para ver la salida aquí.