Putting it together
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
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.
สำรวจ
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.
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a function total(nums) that returns the sum of every number in the array nums.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a function biggest(nums) that returns the largest value in the array.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a function countAbove(nums, limit) that returns how many numbers are มากกว่า limit.
คลิก Run เพื่อดูผลลัพธ์ที่นี่