Putting it together · การรวมกัน
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.
การรวมกัน
- โปรแกรมจริงผสมผสานตัวแปร, ลูป, ฟังก์ชัน, อาร์เรย์ และ object เข้าด้วยกัน
- ลูป
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
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 ที่บวกตัวเลขเข้าด้วยกันทีละตัว
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
Searching and counting
- ลูปผ่านอาร์เรย์ และรักษา เคาน์เตอร์ (หรือ flag) ไว้ขณะเดินลูป
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
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 ให้ทำหน้าที่ของตัวเอง
Now you try
- Write each function using a loop.
- Press Check answer to test it.
ลองดูเลย
- เขียนฟังก์ชันแต่ละตัวโดยใช้ลูป
- กด Check answer เพื่อทดสอบ
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write a function biggest(nums) that returns the largest value in the array. · เขียนฟังก์ชัน biggest(nums) ที่ส่งคืนค่า สูงสุด ในอาเรย์.
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่