This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

In my last article, I learned about the array traversal method forEach(), but there were a few hicks. ES6 – for/of, JS- special symbol – bit operator, JS- logic operator – short circuit? , [JavaScript- arrow function],

In this article, we’ll continue to look at some of the other JavaScript methods for iterating over an array: map(), a common method for iterating over an array, is often used in practice.

JavaScript map()

Documents: Array. The prototype. The map () | MDN

There are many ways to iterate over some data in JavaScript, such as for/in/for/of/forEach, which can be simply written down: for/in traversal object <–> for/of traversal number group. ForEach () is easier to write.

The map () | MDN method creates a new array, as a result, each element in the array is provided a function called after return values.

First, the simplest way to use it is as follows:

const array = [1.2.3.5.8]

array.map((item) = > {
  // Print each element of the array:
  console.log(item)
})
// Outputs: 1, 2, 3, 5, 8

const map1 = array.map((item) = > item * 2)
console.log(map1)
// [2, 4, 6, 10, 16]
console.log(array)
// [1, 2, 3, 5, 8]
Copy the code

As you can see from the code above, the map() method does not alter the array. You can also use the map() method to make a custom copy of the array: for example, the map() method assigns each item of the array by 2 to MAP1

The map () syntax

// Syntax: There are still many arguments
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array
}[, thisArg])
Copy the code
  • callbackA function that generates a new array element, taking three arguments:
  • currentValueThe current element being processed in the callback array.
  • indexThe index of the current element being processed in the optional callback array.
  • arrayAn array of optional map method calls.
  • thisArgOptionally, the value is used as this when the callback function is executed.

The return value of the map() method

Using map() has a return value: a new array consisting of the results of the callback function performed on each element of the original array.

map()Methods:

Copy data (array): You can use map to reformat each item of the array and return..

Here’s a classic interview question:

; ['1'.'2'.'3'].map(parseInt)
Copy the code

This is a simple line of code, expected to output [1, 2, 3], but the actual result is [1, NaN, NaN], this is the problem of map and parseInt parameters, can be explained in the beginning of the MDN document for further study