5 usage scenarios of JavaScript array method .map()

Array.prototype.map()method is an array method in JavaScript that creates a new array, the result of which is to execute the provided function on each element in the calling array.

  • .map() Function used to iterate over array elements. It accepts a callback function as a parameter and returns a new array and new elements based on the callback function.

  • .map() The method is a general method used tocreate a new array, modify its contents, and leave the original array unchanged. It can be used when there is a need to modify the contents of an existing array and store the result as a new variable. .map() The original array will not be transformed.

parameter

callback(必须):生成新数组元素的函数,接收三个参数:

currentValue:callback 数组中正在处理的当前元素。
index:可选,callback 数组中正在处理的当前元素的索引。
array:可选,map 方法调用的数组。
thisArg:可选,执行 callback 函数时值被用作 this 。

return value

  • A new array composed of the results of executing the callback function on each element of the original array.

The .map() method comes in handy when you need to update all items in an array and store them in a new array.

Usage scenarios include but are not limited to:

  1. Convert array elements: You can use .map() to convert each element in an array. For example, multiply each element in an array of numbers by 2:

    const originalArray = [1, 2, 3, 4, 5];
    const doubledArray = originalArray.map(num => num * 2);
    // doubledArray 现在是 [2, 4, 6, 8, 10]
    
  2. Extract attributes: If each element in the array is an object, you can use .map() to extract specific attributes of the object:

    const users = [
      {
          
           id: 1, name: 'Alice' },
      {
          
           id: 2, name: 'Bob' },
      {
          
           id: 3, name: 'Charlie' }
    ];
    
    const userIds = users.map(user => user.id);
    // userIds 现在是 [1, 2, 3]
    
  3. Generate JSX or other templates: In React or similar libraries, you might use .map() to generate JSX elements:

    const names = ['Alice', 'Bob', 'Charlie'];
    
    const nameList = names.map((name, index) => <li key={
          
          index}>{
          
          name}</li>);
    // nameList 是包含 <li> 元素的数组
    
  4. Filter the array: Filter the elements in the array according to certain conditions:

    const numbers = [1, 2, 3, 4, 5];
    
    const evenNumbers = numbers.map(num => num * 2).filter(num => num % 2 === 0);
    // evenNumbers 现在是 [4, 8]
    
  5. Filter array: Convert string to array:

    const language = "China";
    const map = Array.prototype.map;
    const letters = map.call(language, (eachLetter) => `${
          
          eachLetter}`);
    
    console.log(letters); // [ 'C', 'h', 'i', 'n', 'a' ]
    

In general, .map() is a very flexible method, suitable for processing each element in the array and generating a new array.

Guess you like

Origin blog.csdn.net/m0_46672781/article/details/134713968