การแยกโครงสร้างพารามิเตอร์ฟังก์ชันใน JavaScript
การแยกโครงสร้างยังมีการใช้งานที่สำคัญอีกด้านหนึ่งคือ การส่งพารามิเตอร์ให้ฟังก์ชัน สาระสำคัญมีดังนี้: หากฟังก์ชันรับ อาร์เรย์เป็นพารามิเตอร์ เราสามารถกำหนด ในการประกาศฟังก์ชันได้เลยว่าจะแยกโครงสร้าง อาร์เรย์นั้นอย่างไร
มาดูตัวอย่างกัน สมมติว่าเรามี ฟังก์ชันที่รับพารามิเตอร์เป็นอาร์เรย์ ที่มีปี เดือน และวัน:
func([2025, 12, 31]);
เราสามารถระบุในพารามิเตอร์ของฟังก์ชันได้เลยว่า ควรแบ่งอาร์เรย์นี้เป็นตัวแปรอะไรบ้าง:
function func([year, month, day]) {
console.log(year); // แสดงผล 2025
console.log(month); // แสดงผล 12
console.log(day); // แสดงผล 31
}
โครงสร้างข้างต้นควรถูกมองว่าเป็น พารามิเตอร์เดียวของฟังก์ชัน สามารถเพิ่มพารามิเตอร์อื่น ตามต้องการได้:
func('str1', [2025, 12, 31], 'str2');
function func(param1, [year, month, day], param2) {
console.log(param1); // แสดงผล 'str1'
console.log(year); // แสดงผล 2025
console.log(month); // แสดงผล 12
console.log(day); // แสดงผล 31
console.log(param2); // แสดงผล 'str2'
}
ในตัวอย่างถัดไป ฟังก์ชันรับพารามิเตอร์ เป็นอาร์เรย์สองตัวแรกและเราแยกโครงสร้าง ทั้งสอง:
func([2025, 12, 31], [2026, 11, 30]);
function func([year1, month1, day1], [year2, month2, day2]) {
console.log(year1); // แสดงผล 2025
console.log(month1); // แสดงผล 12
console.log(day1); // แสดงผล 31
console.log(year2); // แสดงผล 2026
console.log(month2); // แสดงผล 11
console.log(day2); // แสดงผล 30
}
แก้ไขโค้ดต่อไปนี้โดยใช้การแยกโครงสร้าง ตามทฤษฎีที่เรียนมา:
function func(employee) {
let name = employee[0];
let surname = employee[1];
let department = employee[2];
let position = employee[3];
let salary = employee[4];
}
func( ['John', 'Smit', 'development', 'programmer', 2000] );
แก้ไขโค้ดต่อไปนี้โดยใช้การแยกโครงสร้าง ตามทฤษฎีที่เรียนมา:
function func(employee) {
let name = employee[0];
let surname = employee[1];
let info = employee[2];
}
func( ['John', 'Smit', 'development', 'programmer', 2000] );
แก้ไขโค้ดต่อไปนี้โดยใช้การแยกโครงสร้าง ตามทฤษฎีที่เรียนมา:
function func(employee) {
let name = employee[0];
let surname = employee[1];
let department = employee[2];
let position;
if (arr[3] !== undefined) {
position = arr[3];
} else {
position = 'junior';
}
}
func( ['John', 'Smit', 'development'] );
แก้ไขโค้ดต่อไปนี้โดยใช้การแยกโครงสร้าง ตามทฤษฎีที่เรียนมา:
function func(department, employee, hired) {
let name = employee[0];
let surname = employee[1];
let year = hired[0];
let month = hired[1];
let day = hired[2];
}
func( 'development', ['John', 'Smit'], [2018, 12, 31] );