The use of map function in Array built-in object in JavaScript

一、概念

map() The function itself does not change the original array, but returns a new array after processing the data. The elements in the new array are the return values ​​of each element in the original array after the callback function is executed. In the callback function, the data can be processed as needed and return.

Note: When the original array needs to be modified at the same time, the original array can be reassigned during callback execution.

2. Grammar

arr.map( callback( currentElement, currentIndex, originalArray), thisObj )

illustrate:

        callback is the callback function passed to map(), and it is a required parameter.

        thisObj will be used as the this value of the callback function when passed in, and is an optional parameter

        currentElement refers to the current element of callback, which must pass parameters.

        currentIndex refers to the index of the current element of callback, an optional parameter.

        originalArray refers to the processed array, that is, the original array, an optional parameter.

3. Example

1. Return a new array: composed of 10 times the value of each element in the original array.

let originArray = [ 2, 4, 6, 8 ]

let newArray = originArray.map(function(currentElement){

        return currentElement * 10

})

console.log(newArray) // The output is: [20, 40, 60, 80]

Shorthand:

let newArray = originArray.map( item => (item * 10) )

console.log(newArray) // The output is: [20, 40, 60, 80]

2. Modify the original array: expand the number of each element in the original array by 20 times.

let originArray = [ 2, 4, 6, 8 ]

originArray.map((cur,index) => ( originArray[index] = cur * 20 ) )

console.log(originArray ) // The output is: [40, 80, 120, 160]

        

Guess you like

Origin blog.csdn.net/my__flower/article/details/122083568