<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
const numbers = [273, 23, 42, 152, 35]
numbers.forEach(function(value, index){
console.log(`${index} index : ${value}`)
})
</script>
</head>
<body>
</body>
</html>
- **Array of Numbers**: An array named `numbers` is defined, containing five numerical values: `[273, 23, 42, 152, 35]`.
- **`forEach` Method**: This JavaScript method is called on the `numbers` array. The `forEach` method is used to execute a function for each element in the array. It's a part of JavaScript's `Array` prototype, making it available on all array instances.
- **Callback Function**: The function passed to `forEach` is a callback that takes two parameters: `value` and `index`. For each iteration of `forEach`, `value` represents the current element in the array being processed, and `index` represents the position of that element in the array.
- **`console.log`**: Inside the callback function, a `console.log` statement is used to log a string to the browser's console. This string is constructed using template literals (denoted by backticks \`\`), which allow embedding the values of `index` and `value` directly within the string. The resulting output for each element in the array is of the form "`<index> index : <value>`", where `<index>` and `<value>` are replaced with the actual index and value of each element.
The overall effect of this script is that when the HTML document is loaded in a web browser, the browser's console will display the index and value of each element in the `numbers` array. This is a basic example of iterating through an array in JavaScript and performing an action (in this case, logging to the console) for each element.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
method) private (1) | 2025.01.24 |
---|---|
class) Ractangle class (0) | 2025.01.23 |
method) getter and setter method (0) | 2025.01.21 |
method) JSON.parse() method (0) | 2025.01.20 |
method) JSON.stringify() method (0) | 2025.01.19 |