<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function sample(){
console.log(arguments)
for (let i =0; i< arguments.length ; i++){
console.log(`${i} index : ${arguments[i]}`)
}
}
sample(1,2)
sample(1,2,3)
sample(1,2,3,4)
</script>
</head>
<body>
</body>
</html>
### Script Breakdown
- **Function Definition**: The `sample` function is defined without any formal parameters. Inside the function:
- `console.log(arguments)` logs the entire `arguments` object to the console, showing all arguments passed to the function.
- A `for` loop iterates over the `arguments` object using its `length` property to access each argument by index.
- Inside the loop, `console.log(`${i} index : ${arguments[i]}`)` logs the index of each argument and its value.
### Function Calls
- `sample(1,2)`, `sample(1,2,3)`, and `sample(1,2,3,4)` call the `sample` function with 2, 3, and 4 arguments, respectively.
### Output
When the document is loaded in a web browser, the script automatically calls the `sample` function three times with different sets of arguments. The output in the browser's developer console will be:
1. For `sample(1,2)`:
- An `arguments` object containing `[1, 2]`.
- Logs:
```
0 index : 1
1 index : 2
```
2. For `sample(1,2,3)`:
- An `arguments` object containing `[1, 2, 3]`.
- Logs:
```
0 index : 1
1 index : 2
2 index : 3
```
3. For `sample(1,2,3,4)`:
- An `arguments` object containing `[1, 2, 3, 4]`.
- Logs:
```
0 index : 1
1 index : 2
2 index : 3
3 index : 4
```
### Key Points
- The `arguments` object enables functions to work with an arbitrary number of arguments, which can be particularly useful for functions that need to handle varying amounts of input data.
- Since `arguments` is array-like but not an actual array, it has a `length` property but does not have array methods like `map`, `filter`, or `reduce`. If needed, it can be converted to a real array using `Array.from(arguments)` or the spread operator `[...arguments]`.
- This script effectively demonstrates how to access and use the `arguments` object to process a variable number of function arguments, showcasing a flexible approach to function parameter handling in JavaScript.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 5) Troubleshooting Using Immediately Called Functions (0) | 2024.12.05 |
---|---|
chapter 5) use to remaining parameters make array (0) | 2024.12.04 |
chapter 4) for (0) | 2024.12.02 |
chapter 4) while (0) | 2024.12.01 |
chapter 4) continue (0) | 2024.11.30 |