Home >Web Front-end >JS Tutorial >How to use map function in js
The map() function in JavaScript is a function used to create a new array, which transforms each element in the original array through a specified function. When used, two parameters need to be passed: callback function and original array. The callback function accepts the current element, an optional index, and the array itself, and returns the new transformed value. The map() function can be used for various conversion operations, such as converting a string to uppercase or lowercase, extracting object properties, or filtering elements that meet a condition. It creates new array without modifying the original array and allows to easily perform the same operation on each element in the array.
The map() function in JavaScript
What is the map() function?
The map() function is a JavaScript function that creates a new array by transforming each element in the original array by a specified function.
How to use map() function?
map() function accepts two parameters:
Syntax:
<code class="javascript">const newArray = arr.map((element, index, array) => { // 在此对元素进行变换操作 });</code>
Callback function parameters:
Example:
Suppose we have an array of numbers: [1, 2, 3, 4, 5], and we want to create a new array, Each element in it is increased by 1.
<code class="javascript">const numbers = [1, 2, 3, 4, 5]; const incrementedNumbers = numbers.map((num) => num + 1); // [2, 3, 4, 5, 6]</code>
Other uses:
map() function can also be used for other conversion operations, such as:
Advantages:
The above is the detailed content of How to use map function in js. For more information, please follow other related articles on the PHP Chinese website!