Putting it together
Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
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.
Khám phá
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.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Write a function total(nums) that returns the sum of every number in the array nums.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Write a function biggest(nums) that returns the largest value in the array.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Write a function countAbove(nums, limit) that returns how many numbers are lớn hơn limit.
Nhấn Chạy để xem kết quả ở đây.