Rest Parameters (ES2015/ES6) ช่วยให้ฟังก์ชันรับ จำนวนอาร์กิวเมนต์ไม่จำกัด ได้ โดยรวมอาร์กิวเมนต์ที่เหลือทั้งหมดไว้ใน อาร์เรย์ ใช้สัญลักษณ์ ... (three dots) นำหน้าพารามิเตอร์ตัวสุดท้าย
ไวยากรณ์
function funcName(param1, param2, ...restParams) { ... }
ตัวอย่าง
<html>
<body>
<script>
function addition(...numbers) {
var res = 0;
numbers.forEach(function(number) {
res += number;
});
return res;
}
document.write(addition(3)); // 3
document.write("<br>");
document.write(addition(5, 6, 7, 8, 9)); // 35
</script>
</body>
</html>
ความแตกต่างจาก arguments object
| คุณสมบัติ | Rest Parameters | arguments object |
|---|---|---|
| ชนิดข้อมูล | Array จริง (มี map, filter, reduce, ฯลฯ) | Array-like object (ไม่มีเมธอดอาร์เรย์) |
| ขอบเขต | เฉพาะพารามิเตอร์ที่กำหนด (...rest) | ทุกอาร์กิวเมนต์ที่ส่งมา |
| Arrow Function | ใช้ได้ | ใช้ไม่ได้ (arrow function ไม่มี arguments) |
| Destructuring | รองรับ | ไม่รองรับ |
ตัวอย่างเพิ่มเติม
// รวมกับพารามิเตอร์ปกติ
function greet(greeting, ...names) {
return greeting + " " + names.join(", ");
}
greet("Hello", "A", "B", "C"); // "Hello A, B, C"
// Destructuring กับ rest
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]
แนะนำ: ใช้ Rest Parameters แทน arguments ในโค้ดสมัยใหม่ เพราะเป็น Array จริงและทำงานกับ Arrow Function ได้