Putting it together · 综合运用
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 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.
中文
综合运用
- 真正的程序把变量、循环、函数、数组和对象组合起来。
for...of循环直接读取数组的每个元素 —— 不需要索引。
function total(nums) {
let t = 0;
for (const n of nums) {
t = t + n;
}
return t;
}
console.log(total([4, 8, 6])); // → 18
Explore · 探索
for...of builds the total · for...of 累积出总和
for...of reads each item directly. Watch t add them up, one at a time. · for...of 直接读取每个元素。看着 t 一个一个把它们加起来。
English
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
中文
查找与计数
- 遍历数组,一边走一边保留一个计数器(或一个标志)。
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
English
Common mistakes
- Build in small steps and use
console.logto check as you go. - Keep the HTML, CSS and JavaScript doing their own jobs.
中文
常见错误
- 小步构建,边写边用
console.log检查。 - 让 HTML、CSS 和 JavaScript 各司其职。
English
Now you try
- Write each function using a loop.
- Press Check answer to test it.
中文
现在轮到你
- 用循环写出每个函数。
- 按检查答案来测试它。
Write a function total(nums) that returns the sum of every number in the array nums. · 写一个函数 total(nums),返回数组 nums 中每个数字的和。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a function biggest(nums) that returns the largest value in the array. · 写一个函数 biggest(nums),返回数组中最大的值。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit. · 写一个函数 countAbove(nums, limit),返回有多少个数字大于 limit。
Click Run to see the output here. · 点击“运行”查看此处输出。