<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function sample(...items){
console.log(items)
}
const array = [1,2,3,4]
console.log(sample.array(null, array))
</script>
</head>
<body>
</body>
</html>
1. **`sample` Function Definition**:
- The `sample` function is correctly defined to accept an arbitrary number of arguments using the rest parameter syntax (`...items`). Inside the function, it logs `items`, which would be an array containing all passed arguments.
2. **Attempt to Call `sample` Function**:
- The script attempts to call the `sample` function in a peculiar and incorrect manner: `sample.array(null, array)`. This syntax is not valid in JavaScript for calling a function with arguments. It seems to misunderstand how to pass an array to a function expecting multiple arguments or perhaps how to invoke functions in general.
- The correct way to call the `sample` function with an array of values, ensuring each array element is treated as a separate argument (thanks to the spread syntax), would be:
```javascript
sample(...array);
```
This usage of the spread syntax (`...array`) correctly expands the `array` variable into individual arguments when calling the `sample` function.
3. **Correct Usage**:
- If the intent was to log the array `[1,2,3,4]` using the `sample` function, you should use the spread syntax to expand the array elements into individual arguments, like so:
```javascript
sample(...array);
```
This will call `sample` with the elements of `array` as separate arguments, and inside `sample`, `items` will be an array `[1, 2, 3, 4]`, which will then be logged as intended.
To summarize, the key takeaway here is the distinction between the rest parameter syntax for defining functions that accept an indefinite number of arguments, and the spread syntax for expanding iterables (like arrays) into individual arguments when calling functions. The provided script snippet contains a syntax error in the function call, demonstrating a common pitfall when learning JavaScript's flexible argument handling features.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
function) confirm() (0) | 2025.01.27 |
---|---|
function) prompt() (0) | 2025.01.26 |
class) generate object (0) | 2025.01.25 |
method) private (1) | 2025.01.24 |
class) Ractangle class (0) | 2025.01.23 |