map method in JS array

1. Definition

The map() method returns a new array whose elements are the processed values ​​of the original array elements after calling the function.

2. Grammar

array.map(function(currentValue,index,arr), thisValue)

3. Parameter description

 return value

 4. Usage

The map() method processes elements sequentially in the original array element order.

5. Precautions

map() does not check for empty arrays.

map() doesn't mutate the original array.

6. Explanation of primary application examples

//1、对数组array的每个元素乘2------------------------------
const array = [1, 4, 9, 16];
const mapArray = array.map(x => x * 2);
console.log(mapArray);
//打印 [2, 8, 18, 32]

//2、返回由原数组中每个元素的平方组成的新数组--------------------
const array = [1, 2, 3, 4, 5];
const mapArray = array.map((item) => {
    return item * item;
})
console.log(mapArray);
//打印[1, 4, 9, 16, 25]

7. Merge two arrays into one array object.

const array1 = ['周一','周二','周三','周四','周五','周六','周日']
const array2 = ['1','2','3','4','5','6','7']
const newArr = array1.map((item,index) => {
  return {
    name:item,
    id:array2[index]
  }
})
console.log(newArr)
//打印-------------------------
[
    {
        "name": "周一",
        "id": "1"
    },
    {
        "name": "周二",
        "id": "2"
    },
    {
        "name": "周三",
        "id": "3"
    },
    {
        "name": "周四",
        "id": "4"
    },
    {
        "name": "周五",
        "id": "5"
    },
    {
        "name": "周六",
        "id": "6"
    },
    {
        "name": "周日",
        "id": "7"
    }
]

8. Return the two key values ​​in the concatenated array users.

const users = [
  {firstName : "White", lastName: "Green"},
  {firstName : "Red", lastName: "Pink"},
  {firstName : "Yellow", lastName: "Black"}
];

const userFullnames = users.map(function(element){
    return `${element.firstName} ${element.lastName}`;
})

console.log(userFullnames);
//打印 ["White Green","Red Pink","Yellow Black"]

9. The this value in the map.

const arr = [2, 3, 5, 7]
const newArr = arr.map(function(element, index, array){
    return element * this;
}, 80);
console.log(newArr)
//打印 [160,240,400,560]
//分析:
//function()在每个数组元素上调用该回调,并且该map()方法始终将current element,index当前元 
//素的of和整个array对象传递给它。
//该this参数将在回调函数中使用。默认情况下,其值为undefined。这里this值更改为数字的方法80,如果
//不写this指向的是全局,这种用法还是不常见的,做个了解就行。

Guess you like

Origin blog.csdn.net/a15220216758/article/details/125717697