<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//basic remaining parameters
function sample(...items){
console.log(items)
}
sample(1,2,3)
sample(1,2,3,4)
//remaining parameters and normal parameters
function sample2(a,b,...c){
console.log(a,b,c)
}
sample2(1,2)
sample2(1,2,3)
sample2(1,2,3,4)
</script>
</head>
<body>
</body>
</html>
### Rest Parameters
#### Basic Use of Rest Parameters
- **Function `sample`** uses rest parameters (`...items`) to collect all passed arguments into an array named `items`.
- When `sample(1,2,3)` and `sample(1,2,3,4)` are called, the function logs the `items` array to the console, showing that all provided arguments are gathered into an array. This demonstrates the flexibility of rest parameters in capturing a list of arguments.
#### Rest Parameters with Other Parameters
- **Function `sample2`** takes two standard parameters (`a` and `b`) before the rest parameter (`...c`), illustrating how rest parameters can be used alongside regular parameters.
- `sample2(1,2)` logs `1` for `a`, `2` for `b`, and `[]` (an empty array) for `c`, showing that when no extra arguments are provided, `c` is an empty array.
- `sample2(1,2,3)` and `sample2(1,2,3,4)` show how additional arguments are collected into the `c` array. In these calls, `a` and `b` capture the first two arguments, while the rest parameter `c` captures any additional arguments as an array.
### Output
- **For `sample` Calls**:
- `sample(1,2,3)` outputs `[1, 2, 3]`.
- `sample(1,2,3,4)` outputs `[1, 2, 3, 4]`.
- **For `sample2` Calls**:
- `sample2(1,2)` outputs `1 2 []`, indicating that `a` and `b` captured the arguments, and `c` is an empty array.
- `sample2(1,2,3)` outputs `1 2 [3]`, showing that `c` captures the third argument as an array.
- `sample2(1,2,3,4)` outputs `1 2 [3, 4]`, illustrating that all additional arguments beyond the first two are captured by `c`.
### Key Takeaways
- Rest parameters (`...parameterName`) provide a concise way to work with functions that accept a variable number of arguments, collecting them into an array.
- Rest parameters can be combined with other parameters, but they must appear last in the function definition.
- This feature enhances the flexibility of function definitions, making it easier to write functions that handle different numbers of arguments without needing to explicitly use the `arguments` object.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 5) strict mode (0) | 2024.12.06 |
---|---|
chapter 5) Troubleshooting Using Immediately Called Functions (0) | 2024.12.05 |
chapter 5) arguments (0) | 2024.12.03 |
chapter 4) for (0) | 2024.12.02 |
chapter 4) while (0) | 2024.12.01 |