Array methods · เมทოდของอาเรย์ (Array methods)
Array methods
.map(fn)makes a new array by transforming each item..filter(fn)makes a new array of only the items wherefnreturnstrue..forEach(fn)runsfnfor each item, making no new array.
วิธีของอาร์เรย์ (Array methods)
.map(fn)สร้าง อาร์เรย์ใหม่ โดยการแปลงแต่ละองค์ประกอบ.filter(fn)สร้างอาร์เรย์ใหม่ที่มีเฉพาะองค์ประกอบที่fnส่งกลับtrue.forEach(fn)จะรันfnสำหรับแต่ละรายการ โดยไม่สร้าง array ใหม่
let nums = [1, 2, 3];
let doubled = nums.map((n) => n * 2);
console.log(doubled); // → [2,4,6]
Filtering keeps some items
.filterkeeps each item for which the test returnstrue.
การกรองเก็บบางองค์ประกอบไว้
.filterเก็บแต่ละองค์ประกอบที่การทดสอบส่งกลับtrue
let nums = [3, 7, 2, 9];
let big = nums.filter((n) => n > 4);
console.log(big); // → [7,9]
Watch out
.mapand.filterreturn a new array — the original is untouched.- You hand each one an arrow function that says what to do with one item.
ระวัง
.mapและ.filterส่งกลับ อาร์เรย์ใหม่ — อาร์เรย์เดิมไม่ถูกเปลี่ยนแปลง- คุณส่งฟังก์ชันลูกศรเข้าไปเพื่อระบุว่าควรทำอย่างไรกับองค์ประกอบหนึ่ง
Common mistakes
mapandfilterreturn a NEW array — they do not change the original.forEachjust loops and returns nothing.
ข้อผิดพลาดที่พบบ่อย
mapและfilterส่งกลับ ARREY ใหม่ — ไม่เปลี่ยนค่าเดิมforEachทำเพียงลูปและไม่ส่งค่าอะไรกลับมาเลย
Now you try
- Use
.map,.filteror.forEach. - Press Check answer to test it.
ลองดูเลย
- ใช้
.map,.filterหรือ.forEach - กด Check answer เพื่อทดสอบ
Use .map to double every number in [1, 2, 3] and store the new array in result (it should be [2, 4, 6]). · ใช้ .map เพื่อคูณสองทุกตัวเลขใน [1, 2, 3] และจัดเก็บอาเรย์ใหม่ลงใน result (ควรจะเป็น [2, 4, 6]).
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use .filter to keep only the numbers greater than 4 from [3, 7, 2, 9, 1], in a variable big (it should be [7, 9]). · ใช้ .filter เพื่อเก็บเฉพาะตัวเลขที่มีค่า มากกว่า 4 จาก [3, 7, 2, 9, 1] ลงในตัวแปร big (ควรจะเป็น [7, 9]).
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use .forEach to add every number in [4, 8, 15] to total (it should end up 27). · ใช้ .forEach เพื่อบวกตัวเลขทุกตัวใน [4, 8, 15] เข้ากับ total (ควรมีค่าสุดท้ายเป็น 27)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่