Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the map function in the Array built-in object in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 12:02:57 09月24日 Update

This article mainly introduces the relevant knowledge of "how to use the map function in the Array built-in object in JavaScript". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope that this article "how to use the map function in the Array built-in object in JavaScript" can help you solve the problem.

I. concept

The map () 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 value of each element in the original array after executing the callback function, in which the data can be processed and returned as needed.

Note: when you need to modify the original array at the same time, you can reassign the original array during callback execution.

II. Grammar

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

Description:

Callback is a callback function passed in map () and is a required parameter.

When thisObj is passed in, it will be used as the this value of the callback function, which is an optional parameter.

CurrentElement refers to the current element of callback. Parameters are required.

CurrentIndex refers to the index of the current element of the callback, optional parameters.

OriginalArray refers to the array being processed, that is, the original array, with optional parameters.

III. Examples

1. Returns the new array: consisting 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) / / output result is: [20,40,60,80]

Abbreviated method:

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

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

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

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

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

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

This is the end of the introduction to "how to use the map function in the Array built-in object in JavaScript". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Array function element parameter object knowledge result processing output data industry process different practical content at the same time practical actual numerical digital Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Technology MariaDB macOS Redmi