The use of map() function in js

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

关键词:map

In the project, we often encounter the need to modify the data returned by the backend to meet the needs of our front-end developers. Among them, map is an important function that is commonly used to modify array elements.


提示:以下是本篇文章正文内容,下面案例可供参考

1. Concept

The map() method is defined in the Array of JavaScript, which returns a new array, and the elements in the array are the values ​​processed by calling the function of the original array. It is worth noting that: 1. The map() function will not detect an empty array; 2. The map() function will not change the original array, it forms a new array


2. Relevant grammar

array.map(function(currentValue, index, arr), thisIndex)—Parameter
description:

  • function(currentValue, index, arr): Required . For a function, each element in the array will execute this function. where the function parameters are:
  1. currentValue: Required . Represents the value of the current element (item)
  2. index: optional . The index of the current element is the number of array elements.
  3. arr: optional . the array object the current element belongs to
  • thisValue: optional . The object used as the execution callback, passed to the function, used as the value of "this"

3. Example

Example 1: Square the elements of the original array and assign them to the new array

let array = [1, 2, 3, 4, 5];

let newArray = array.map((item) => {
    
    
    return item * item;
})

console.log(newArray)  // [1, 4, 9, 16, 25]

Example 2: Convert data of type int to string type

this.tableData = list.map(function (item) {
    
    
                if (item.leaseStatus === 0) {
    
    
                  item.leaseStatus = '已租';
                } else if (item.leaseStatus === 1) {
    
    
                  item.leaseStatus = '未租';
                } else if (item.leaseStatus === 2) {
    
    
                  item.leaseStatus = '已租';
                }
                if (res.data.data === null) {
    
    
                  item = '暂无记录';
                }
                return item;
              });

at last

Remember to like it if it is helpful to you ! Thanks

Guess you like

Origin blog.csdn.net/daishu_shu/article/details/124127709