Rest parameter cho phép đại diện nhiều argument thành array. ES6 đưa ra để dễ dàng cho dev. Ký hiệu ... trước tên tham số.
Ví dụ
<html>
<body>
<script>
function addition(...numbers) {
var res = 0;
numbers.forEach(function(number) {
res += number;
});
return res;
}
document.write(addition(3)); // 3
document.write(addition(9,10,11,12,13)); // 55
</script>
</body>
</html>
Cú pháp chung
function functionName(param1, param2, ...restParams) {
// restParams là Array chứa các argument từ vị trí 3 trở đi
}
Quy tắc
- Rest parameter phải là tham số cuối cùng.
- Chỉ được một rest parameter mỗi function.
- Không dùng được với
argumentsobject trong cùng function (rest thay thế arguments). - Arrow function hỗ trợ:
const fn = (...args) => { ... }.
Ví dụ nâng cao
// 1. Với named parameters
function greet(greeting, ...names) {
return names.map(name => `${greeting}, ${name}!`).join(' ');
}
greet("Hello", "Alice", "Bob", "Charlie");
// "Hello, Alice! Hello, Bob! Hello, Charlie!"
// 2. Destructuring rest
const [first, second, ...others] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(others); // [3, 4, 5]
// 3. Array destructuring trong parameter (ES2015)
function foo([first, ...rest]) {
console.log(first, rest);
}
foo([1, 2, 3]); // 1, [2, 3]
Rest Parameter vs Default Parameter
function test(a = 1, ...rest) {
console.log(a, rest);
}
test(); // 1, []
test(5); // 5, []
test(5, 6, 7); // 5, [6, 7]