map中放数组,遍历_如何使用.map()遍历JavaScript中的数组项

news/2024/7/5 9:43:16

map中放数组,遍历

介绍 (Introduction)

From the classic forloop to the forEach() method, various techniques and methods are used to iterate through datasets in JavaScript. One of the most popular methods is the .map() method. .map() creates an array from calling a specific function on each item in the parent array. .map() is a non-mutating method that creates a new array as opposed to mutating methods, which only make changes to the calling array.

从经典的forloopforEach()方法,各种技术和方法都用于遍历JavaScript中的数据集。 .map()方法是最受欢迎的方法之一。 .map()通过在父数组中的每个项目上调用特定函数来创建数组。 .map()是一种非变异方法,它创建一个新数组,而不是仅对调用数组进行更改的变异方法。

This method can have many uses when working with arrays. In this tutorial, you’ll look at four noteworthy uses of .map() in JavaScript: calling a function of array elements, converting strings to arrays, rendering lists in JavaScript libraries, and reformatting array objects.

使用数组时,此方法可以有很多用途。 在本教程中,您将看到JavaScript中.map()四个值得注意的用法:调用数组元素的函数,将字符串转换为数组,在JavaScript库中呈现列表以及重新格式化数组对象。

先决条件 (Prerequisites)

This tutorial does not require any coding, but if you are interested in following along with the examples, you can either use the Node.js REPL or browser developer tools.

本教程不需要任何编码,但是如果您对示例感兴趣,可以使用Node.js REPL或浏览器开发人员工具。

  • To install Node.js locally, you can follow the steps at How to Install Node.js and Create a Local Development Environment.

    要在本地安装Node.js,可以按照如何安装Node.js和创建本地开发环境中的步骤进行操作。

  • Chrome DevTools are available by downloading and installing the latest version of Google Chrome.

    可通过下载并安装最新版本的Google Chrome来使用Chrome DevTools 。

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

.map() 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, you can modify each item in an array and create a new function.

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

Here’s an example:

这是一个例子:

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

console.log(sweeterArray)

This output is logged to the console:

此输出记录到控制台:


   
Output
[ 4, 6, 8, 10, 70 ]

This can 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);

The same output is logged to the console:

相同的输出记录到控制台:


   
Output
[ 4, 6, 8, 10, 70 ]

Having code like sweetArray.map(makeSweeter) makes your code a bit more readable.

拥有sweetArray.map(makeSweeter)的代码可使您的代码更具可读性。

步骤2 —将字符串转换为数组 (Step 2 — Converting a String to an Array)

.map() is known to belong to the array prototype. In this step you will use it to convert a string to an array. You are not developing the method to work for strings here. Rather, you will use the special .call() method.

.map()属于数组原型。 在此步骤中,您将使用它将字符串转换为数组。 您不是在这里开发用于字符串的方法。 相反,您将使用特殊的.call()方法。

Everything in JavaScript is an object, and methods are functions attached to these objects. .call() allows you to use the context of one object on another. Therefore, you 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.

.call()可以传递要使用的上下文的参数以及原始函数的参数的参数。

Here’s an example:

这是一个例子:

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

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

console.log(newName)

This output is logged to the console:

此输出记录到控制台:

Output
输出量
  • [ "Sa", "aa", "ma", "ma", "ya" ]

    [“ Sa”,“ aa”,“ ma”,“ ma”,“ ya”]

Here, you used the context of .map() on a string and passed an argument of the function that .map() expects.

在这里,您在字符串上使用了.map()的上下文,并传递了.map()期望的函数的参数。

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

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

第3步-JavaScript库中的呈现列表 (Step 3 — Rendering Lists in JavaScript Libraries)

JavaScript libraries like React use .map() to render items in a list. This requires JSX syntax, however, as the .map() method is wrapped in JSX syntax.

像React这样JavaScript库使用.map()来呈现列表中的项目。 但是,这需要JSX语法,因为.map()方法包装在JSX语法中。

Here’s an example of a React component:

这是一个React组件的示例:

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

const names = ["whale", "squid", "turtle", "coral", "starfish"];

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

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

This is a 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中的无状态组件,该组件使用列表呈现div 。 使用.map()渲染各个列表项,以迭代最初创建的名称数组。 使用ReactDOM在具有root Id的DOM元素上呈现此组件。

第4步-重新格式化数组对象 (Step 4 — Reformatting Array Objects)

.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.

.map()可用于遍历数组中的对象,并以类似于传统数组的方式修改每个单独对象的内容并返回一个新数组。 根据回调函数返回的内容进行此修改。

Here’s an example:

这是一个例子:

const myUsers = [
    { name: 'shark', likes: 'ocean' },
    { name: 'turtle', likes: 'pond' },
    { name: 'otter', likes: 'fish biscuits' }
]

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

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

    return container;
})

console.log(usersByLikes);

This output is logged to the console:

此输出记录到控制台:


   
Output
[ {shark: "ocean", age: 50}, {turtle: "pond", age: 60}, {otter: "fish biscuits", age: 50} ]

Here, you modified 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 tutorial, we looked at four uses of the .map() method in JavaScript. In combination with other methods, the functionality of .map() can be extended. For more information, see our How To Use Array Methods in JavaScript: Iteration Methods article.

在本教程中,我们研究了JavaScript中.map()方法的四种用法。 与其他方法结合使用,可以扩展.map()的功能。 有关更多信息,请参见我们的如何在JavaScript中使用数组方法:迭代方法一文。

翻译自: https://www.digitalocean.com/community/tutorials/4-uses-of-javascripts-arraymap-you-should-know

map中放数组,遍历


http://www.niftyadmin.cn/n/3648140.html

相关文章

分布式开源调度框架TBSchedule详解

主要内容&#xff1a;第一部分 TBSchedule基本概念及原理 1. 概念介绍 2. 工作原理 3. 源码分析 4. 与其他开源调度框架对比第二部分 TBSchedule分布式调度示例 1. TBSchedule源码下载 2. 引入源码Demo开发示例 3. 控制台配置任务调度 4. selectTasks方法参数说…

如何打组合竞争力的牌

by zhengyun_ustc 20060712本期《人力资本》就“组合竞争力”洋洋洒洒了三页纸&#xff0c;举的最招人的例子就是徐静蕾&#xff0c;演员/导演/歌手/博客&#xff0c;每一个单拎出来她都不是最强的&#xff0c;但是你必须承认老徐是大红人而且还招人待见&#xff0c;为什么呢&a…

如何让我们在Ubuntu 20.04上加密来保护Nginx

介绍 (Introduction) Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free TLS/SSL certificates, thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot…

Docker基本概念详解

本文只是对Docker的概念做了较为详细的介绍&#xff0c;并不涉及一些像Docker环境的安装以及Docker的一些常见操作和命令。阅读本文大概需要15分钟&#xff0c;通过阅读本文你将知道一下概念&#xff1a;容器什么是Docker&#xff1f;Docker思想、特点Docker容器主要解决什么问…

Nokia S60如何处理302 HTTP状态[J2ME]

[j2me] Nokia S60如何处理302 HTTP状态历史VersionDateCreatorDescription1.0.0.1 2006-7-24郑昀第一稿1 Nokia S60如何处理302HTTP状态HttpConnection/302/ HTTP_TEMP_REDIRECT关键词详细描述当用HttpConnection读取远端数据&#xff0c;而远端返回状态码302表示重定向时&…

docker 容器共享数据_如何在Docker容器之间共享数据

docker 容器共享数据介绍 (Introduction) Docker is a popular containerization tool used to provide software applications with a filesystem that contains everything they need to run. Using Docker containers ensures that the software will behave the same way r…

SpringBoot的官方英文介绍(中文译本)

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". 翻译&#xff1a;SpringBoot可以很简单的创建一个基于项目的单机版&#xff0c;生产环境水平的Spring框架&#xff0c;从而让你的项目运行…

X Window研究笔记(20)

X Window研究笔记(20)转载时请注明出处和作者联系方式作者联系方式&#xff1a;李先静 20.X Window资源管理在X Window中&#xff0c;资源是一个广泛使用的概念。它包括图片、光标和窗口等对象&#xff0c;可以是内置的&#xff0c;也可以是注册的。每个资源都有一个ID&#xf…