Array methods · Các phương thức mảng
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.
Phương pháp mảng
.map(fn)tạo ra một mảng mới bằng cách biến đổi từng mục..filter(fn)tạo ra một mảng mới chỉ chứa các mục màfntrả vềtrue..forEach(fn)thực thifncho từng mục, không tạo mảng mới.
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.
Lọc giữ lại một số mục
.filtergiữ lại mỗi mục mà tại đó bài kiểm tra trả về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.
Lưu ý
.mapvà.filtertrả về một mảng mới — mảng gốc không bị thay đổi.- Bạn truyền cho mỗi cái một hàm mũi tên nói lên việc phải làm gì với một mục.
Common mistakes
mapandfilterreturn a NEW array — they do not change the original.forEachjust loops and returns nothing.
Lỗi thường gặp
mapvàfiltertrả về MỘT MẢNG MỚI — chúng không thay đổi mảng gốc.forEachchỉ duyệt qua và không trả về gì cả.
Now you try
- Use
.map,.filteror.forEach. - Press Check answer to test it.
Bây giờ bạn thử
- Sử dụng
.map,.filterhoặc.forEach. - Nhấn Kiểm tra đáp án để thử nghiệm.
Use .map to double every number in [1, 2, 3] and store the new array in result (it should be [2, 4, 6]). · Sử dụng .map để nhân đôi mỗi số trong [1, 2, 3] và lưu mảng mới vào result (nó sẽ là [2, 4, 6]).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
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]). · Sử dụng .filter để giữ lại chỉ các số lớn hơn 4 từ [3, 7, 2, 9, 1], trong biến big (nó sẽ là [7, 9]).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Use .forEach to add every number in [4, 8, 15] to total (it should end up 27). · Sử dụng .forEach để cộng mỗi số trong [4, 8, 15] với total (kết quả cuối cùng sẽ là 27).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.