您应该知道JavaScript的Array.map()的4种用法

From the classic forloop to the forEach() method, various techniques and methods used to iterate through datasets abound JavaScript. However, one of the more popular methods is the .map() method.

从经典的forloopforEach()方法,各种各样的技术和用于迭代数据集的方法和JavaScript都很多。 但是,较流行的方法之一是.map()方法。

.map() creates an array from calling a specific function on each item in the parent array. .map() is a non-mutating method in that it creates a new array as against mutating methods which only make changes to the calling array. This can be tricky to remember.

.map()通过在父数组中的每个项目上调用特定函数来创建数组。 .map()是一种非变异方法,因为它创建了一个新的数组,而不是仅对调用数组进行更改的变异方法。 要记住这可能很棘手。

In this post, we'll look at 4 noteworthy uses of the .map() in JavaScript. Let's begin!

在本文中,我们将介绍JavaScript中.map() 4种值得注意的用法。 让我们开始!

在数组中的每个项目上调用函数 ( Calling a Function on Each Item in an Array )

.map() as earlier stated accepts a callback function as one of its arguments and an important parameter of that function is the current value of the item being processed by the function. This is a required parameter. With this parameter, we can modify each individual item in an array and create a new function off it. Here's an example:

如前所述, .map()接受回调函数作为其参数之一,该函数的重要参数是该函数正在处理的项目的当前值。 这是一个必需的参数。 使用此参数,我们可以修改数组中的每个项目,并根据该项目创建一个新函数。 这是一个例子:

const sweetArray = [2, 3, 4, 5, 35]
const sweeterArray = sweetArray.map(sweetItem => {
    return sweetItem * 2
})

console.log(sweeterArray) // [4, 6, 8, 10, 70]

This can even be simplified further to make it cleaner with:

甚至可以进一步简化它,使其更干净:

// create a function to use
const makeSweeter = sweetItem => sweetItem * 2;

// we have an array
const sweetArray = [2, 3, 4, 5, 35];

// call the function we made. more readable
const sweeterArray = sweetArray.map(makeSweeter);

console.log(sweeterArray); // [4, 6, 8, 10, 70]

Having code like sweetArray.map(makeSweeter) makes that a bit more readable when you jump into this code.

拥有像sweetArray.map(makeSweeter)这样的代码,当您跳入该代码时,它的可读性会更高。

将字符串转换为数组 ( Converting a String to an Array )

.map() is known to belong to the Array prototype. How about we use it to convert a String to an Array. Not to worry, we are not developing the method again to work for strings rather we will use the special .call() method.

.map()属于Array原型。 我们如何使用它来将字符串转换为数组。 不用担心,我们不会再开发用于字符串的方法,而是将使用特殊的.call()方法。

Everything in JavaScript is an object and methods are just functions attached to these objects. .call() allows us to utilize the context of one object on another. Therefore, we would be copying the context of .map() in an array over to a string.

JavaScript中的所有内容都是一个对象,方法只是附加到这些对象的函数。 .call()允许我们利用一个对象在另一个对象上的上下文。 因此,我们将数组中的.map()上下文复制到字符串中。

.call() can be passed arguments of, the context to be used, and "parameters for the arguments of the original function". Sounds like gibberish? Here's an example.

可以传递.call()参数,要使用的上下文和“原始函数的参数的参数”。 听起来像胡言乱语? 这是一个例子。

const name = "Chuloo"
const map = Array.prototype.map

const newName = map.call(name, eachLetter => {
    return `${eachLetter}a`
})

console.log(newName) // ["Ca", "ha", "ua", "la", "oa", "oa"]

Here, we simply used the context of .map() on a String and passed an argument of the function which .map() expects. Voila! We have a wolf-lang looking characters in our console. Yikes!

在这里,我们仅在字符串上使用.map()的上下文,并传递了.map()期望的函数参数。 瞧! 我们的控制台中有一个狼狼般的角色。 kes!

This functions like the .split() method of a String only that each individual string characters can be modified before being returned in an array.

此函数的功能类似于String的.split()方法,只是每个单独的字符串字符都可以在数组中返回之前进行修改。

JavaScript库中的渲染列表 ( Rendering Lists in JavaScript Libraries )

JavaScript libraries like React utilize .map() to render items in a list. This requires JSX syntax however as .map() method is wrapped in mustache-like JSX syntax. Here's a good example of a React component.

像React这样JavaScript库利用.map()呈现列表中的项目。 这需要JSX语法,但是.map()方法使用类似胡须的JSX语法包装。 这是一个React组件的好例子。

import React from "react";
import ReactDOM from "react-dom";

const names = ["john", "sean", "mike", "jean", "chris"];

const NamesList = () => (
  <div>
    <ul>{names.map(name => <li key={name}> {name} </li>)}</ul>
  </div>
);

const rootElement = document.getElementById("root");
ReactDOM.render(<NamesList />, rootElement);

Are you unfamiliar with React? This is a simple stateless component in React which renders a div with a list. The individual list items are rendered using .map() to iterate over the names array initially created. This component is rendered using ReactDOM on the DOM element with id of root.

您不熟悉React吗? 这是React中的一个简单的无状态组件,它使用列表呈现div。 使用.map()渲染各个列表项,以迭代最初创建的名称数组。 使用ReactDOM在ID为root的DOM元素上呈现此组件。

重新格式化数组对象 ( Reformatting Array Objects )

How about handling objects in an array? .map() can be used to iterate through objects in an array and in a similar fashion to traditional arrays, *modify the content of each individual object *and return a new array. This modification is done based on what is returned in the callback function. Here's an example:

如何处理数组中的对象? .map()可用于遍历数组中的对象,并以与传统数组类似的方式进行迭代,* 修改每个对象的内容*并返回一个新数组。 根据回调函数返回的内容进行此修改。 这是一个例子:

const myUsers = [
    { name: 'chuloo', likes: 'grilled chicken' },
    { name: 'chris', likes: 'cold beer' },
    { name: 'sam', likes: 'fish biscuits' }
]

const usersByFood = myUsers.map(item => {
    const container = {};

    container[item.name] = item.likes;
    container.age = item.name.length * 10;

    return container;
})


console.log(usersByFood);
// [{chuloo: "grilled chicken", age: 60}, {chris: "cold beer", age: 50}, {sam: "fish biscuits", age: 30}]

All we did is simply modify each object in the array using the bracket and dot notation. This use case can be employed to process or condense received data before being saved or parsed on a frontend application.

我们所做的只是使用括号和点表示法修改数组中的每个对象。 此用例可用于在前端应用程序上保存或解析之前处理或压缩接收到的数据。

结论 (Conclusion)

In this post, we looked at for main uses of the .map() method in JavaScript. A thing to note is that in combination with other methods, the functionality of .map() can be extended and utilized powerfully. Try to find out more use cases. Leave your comments, questions, and feedback in the comments section, they'll be appreciated!

在本文中,我们研究了JavaScript中.map()方法的主要用途。 需要注意的是,与其他方法结合使用时, .map()的功能可以得到扩展和有效利用。 尝试找出更多用例。 将您的评论,问题和反馈留在评论部分,我们将不胜感激!

翻译自: https://scotch.io/tutorials/4-uses-of-javascripts-arraymap-you-should-know

你可能感兴趣的:(您应该知道JavaScript的Array.map()的4种用法)