แผนที่อาร์เรย์ JavaScript ()
ตัวอย่าง
ส่งคืนอาร์เรย์ใหม่ด้วยค่ารากที่สองของค่าองค์ประกอบทั้งหมด:
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt)
คูณค่าทั้งหมดในอาร์เรย์ด้วย 10:
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 10;
}
ตัวอย่างเพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
map()
สร้างอาร์เรย์ใหม่จากการเรียกใช้ฟังก์ชันสำหรับทุกองค์ประกอบอาร์เรย์
map()
เรียกใช้ฟังก์ชันหนึ่งครั้งสำหรับแต่ละองค์ประกอบในอาร์เรย์
map()
ไม่เรียกใช้ฟังก์ชันสำหรับองค์ประกอบว่าง
map()
ไม่เปลี่ยนอาร์เรย์เดิม
ไวยากรณ์
array.map(function(currentValue, index, arr), thisValue)
พารามิเตอร์
Parameter | Description |
function() | Required. A function to be run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default value undefined .A value passed to the function to be used as its this value. |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
อาร์เรย์ | ผลลัพธ์ของฟังก์ชันสำหรับแต่ละองค์ประกอบอาร์เรย์ |
รองรับเบราว์เซอร์
map()
เป็นคุณลักษณะ ECMAScript5 (ES5)
ES5 (JavaScript 2009) รองรับทุกเบราว์เซอร์:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
ตัวอย่างเพิ่มเติม
รับชื่อเต็มสำหรับแต่ละคน:
const persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
persons.map(getFullName);
function getFullName(item) {
return [item.firstname,item.lastname].join(" ");
}