เมธอด Array.from() ใช้สำหรับ สร้างอินสแตนซ์อาร์เรย์ใหม่ จากอ็อบเจกต์ที่มีคุณสมบัติ length หรืออ็อบเจกต์ที่เป็น Iterable (เช่น Map, Set, String, arguments, NodeList)
ไวยากรณ์ (Syntax)
Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike- อ็อบเจกต์ที่ต้องการแปลงเป็นอาร์เรย์mapFn(ตัวเลือก) - ฟังก์ชัน map เรียกใช้กับแต่ละองค์ประกอบthisArg(ตัวเลือก) - ค่าthisให้กับmapFn
ตัวอย่างการใช้งาน
ตัวอย่างที่ 1: แปลง String เป็นอาร์เรย์
<!DOCTYPE html>
<html>
<body>
<h2>Array.from กับ String</h2>
<p id="demo"></p>
<script>
const arr1 = Array.from("PQRS");
const arr2 = Array.from("12345");
document.getElementById("demo").innerHTML = arr1 + " และ " + arr2;
// ผลลัพธ์: P,Q,R,S และ 1,2,3,4,5
</script>
</body>
</html>
ตัวอย่างที่ 2: ใช้กับ map function
<!DOCTYPE html>
<html>
<body>
<h2>Array.from พร้อม Map Function</h2>
<p id="demo"></p>
<script>
// แปลงตัวเลขในสตริงเป็นตัวเลขจริงและคูณ 2
const numbers = Array.from("1234", x => Number(x) * 2);
document.getElementById("demo").innerHTML = numbers;
// ผลลัพธ์: 2,4,6,8
</script>
</body>
</html>
ตัวอย่างที่ 3: แปลง NodeList / Arguments
// แปลง NodeList จาก querySelectorAll เป็นอาร์เรย์
const nodes = document.querySelectorAll('div');
const nodesArray = Array.from(nodes);
// แปลง arguments object เป็นอาร์เรย์
function sum() {
const args = Array.from(arguments);
return args.reduce((a, b) => a + b, 0);
}
กรณีใช้งานทั่วไป (Use Cases)
- แปลง
argumentsobject เป็นอาร์เรย์จริง - แปลง
NodeList/HTMLCollectionจาก DOM - สร้างอาร์เรย์จาก
SetหรือMap - สร้างอาร์เรย์ขนาดคงที่พร้อมค่าเริ่มต้น:
Array.from({length: 5}, (_, i) => i)→[0,1,2,3,4]