<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
let numbers = [124,235,356,546,23]
numbers = numbers.map(function (value,index){
return value * value
})
numbers.forEach(console.log)
</script>
</head>
<body>
</body>
</html>
1. **Initialization of the Array**: An array named `numbers` is initialized with five integer values: 124, 235, 356, 546, and 23.
2. **Mapping to Square Values**: The `numbers` array is then transformed using the `map` function. For each element in the array, the function takes the element's value (`value`) and its index (`index`), squares the value (`value * value`), and returns this squared value. The result is a new array where each element is the square of the corresponding element in the original `numbers` array. This new array replaces the original `numbers` array due to the assignment `numbers = numbers.map(...)`.
3. **Logging Each Element to the Console**: The `forEach` method is then used to log each element of the squared `numbers` array to the console. The `console.log` function is passed as the callback function to `forEach`, which means each element (along with its index and the entire array) will be logged to the console.
### How `forEach` Works in This Context
- The `forEach` method executes the provided function (`console.log` in this case) once for each array element.
- Since `console.log` is being used directly as the callback, it will receive three arguments for each invocation:
- The current element value (the squared number),
- The current index,
- The array being traversed.
- As a result, you will see console output for each element that includes the element value, its index in the array, and a reference to the entire array.
### Expected Console Output
For each element in the `numbers` array, the console will output something like the following (the actual values will vary since the numbers are squared):
```
15376 0 (5) [15376, 55225, 126736, 298116, 529] VMXXX:9
55225 1 (5) [15376, 55225, 126736, 298116, 529] VMXXX:9
126736 2 (5) [15376, 55225, 126736, 298116, 529] VMXXX:9
298116 3 (5) [15376, 55225, 126736, 298116, 529] VMXXX:9
529 4 (5) [15376, 55225, 126736, 298116, 529] VMXXX:9
```
This output shows the squared value, its index in the array, and the complete array for each element, demonstrating how the `forEach` method and `console.log` function work together to provide detailed information about the array's elements.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
method) JSON.stringify() method (0) | 2025.01.19 |
---|---|
method) Lodash_sortBy() method (1) | 2025.01.18 |
method) Math.random() method (0) | 2025.01.16 |
method) prototype method (1) | 2025.01.15 |
method) querySelector() (0) | 2025.01.14 |