此页面需较新浏览器(支持 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.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write a function biggest(nums) that returns the largest value in the array.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write a function countAbove(nums, limit) that returns how many numbers are 大于 limit.
点击“运行”查看此处输出。