归约归约冲突_JavaScript映射,归约和过滤-带有代码示例的JS数组函数

归约归约冲突

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why and how to use each one.

映射,缩小和过滤都是JavaScript中的数组方法。 每个人都将遍历一个数组并执行转换或计算。 每个函数都将根据函数的结果返回一个新数组。 在本文中,您将学习为什么以及如何使用每一项。

Here is a fun summary by Steven Luscher:

这是史蒂文·卢切尔(Steven Luscher)的有趣总结:

地图 (Map)

The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.

map()方法用于从现有数组创建新数组,并将函数应用于第一个数组的每个元素。

句法 (Syntax)

var new_array = arr.map(function callback(element, index, array) {// Return value for new_array
}[, thisArg])

In the callback, only the array element is required. Usually some action is performed on the value and then a new value is returned.

在回调中,仅需要array element 。 通常,对该值执行一些操作,然后返回一个新值。

(Example )

In the following example, each number in an array is doubled.

在下面的示例中,数组中的每个数字都加倍。

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]

过滤 (Filter)

The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

filter()方法获取数组中的每个元素,并对其应用条件语句。 如果此条件返回true,则该元素将被推送到输出数组。 如果条件返回false,则不会将元素压入输出数组。

句法 (Syntax)

var new_array = arr.filter(function callback(element, index, array) {// Return true or false
}[, thisArg])

The syntax for filter is similar to map, except the callback function should return true to keep the element, or false otherwise. In the callback, only the element is required.

filter的语法类似于map ,不同之处在于回调函数应返回true以保留该元素,否则返回false 。 在回调中,仅需要element

例子 (Examples)

In the following example, odd numbers are "filtered" out, leaving only even numbers.

在下面的示例中,“滤除”了奇数,仅保留了偶数。

const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]

In the next example, filter() is used to get all the students whose grades are greater than or equal to 90.

在下一个示例中, filter()用于获取所有成绩大于或等于90的学生。

const students = [{ name: 'Quincy', grade: 96 },{ name: 'Jason', grade: 84 },{ name: 'Alexis', grade: 100 },{ name: 'Sam', grade: 65 },{ name: 'Katie', grade: 90 }
];const studentGrades = students.filter(student => student.grade >= 90);
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]

减少 (Reduce)

The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.

reduce()方法将值数组减少为一个值。 为了获得输出值,它在数组的每个元素上运行一个reducer函数。

句法 (Syntax)

arr.reduce(callback[, initialValue])

The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

callback参数是一个函数,将为数组中的每个项目调用一次。 该函数有四个参数,但通常仅使用前两个参数。

  • accumulator - the returned value of the previous iteration

    累加器 -上一次迭代的返回值

  • currentValue - the current item in the array

    currentValue-数组中的当前项目

  • index - the index of the current item

    index-当前项目的索引

  • array - the original array on which reduce was called

    array-在其上调用reduce的原始数组

  • The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.

    initialValue参数是可选的。 如果提供的话,它将在第一次调用回调函数时用作初始累加器值。

例子 (Examples)

The following example adds every number together in an array of numbers.

下面的示例将每个数字加在一起组成一个数字数组。

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {return result + item;
}, 0);
console.log(sum); // 10

In the next example, reduce() is used to transform an array of strings into a single object that shows how many times each string appears in the array. Notice this call to reduce passes an empty object {} as the initialValue parameter. This will be used as the initial value of the accumulator (the first argument) passed to the callback function.

在下一个示例中, reduce()用于将字符串数组转换为单个对象,该对象显示每个字符串出现在数组中的次数。 注意,该reduce调用将空对象{}作为initialValue参数传递。 这将用作传递给回调函数的累加器(第一个参数)的初始值。

var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];var petCounts = pets.reduce(function(obj, pet){if (!obj[pet]) {obj[pet] = 1;} else {obj[pet]++;}return obj;
}, {});console.log(petCounts); /*
Output:{ dog: 2, chicken: 3, cat: 1, rabbit: 1 }*/

影片说明 (Video Explanation)

Check out the video below from the freeCodeCamp.org YouTube channel. It covers the array methods discussed, plus a few more.

观看以下来自freeCodeCamp.org YouTube频道的视频。 它涵盖了讨论的数组方法以及其他一些方法。

翻译自: https://www.freecodecamp.org/news/javascript-map-reduce-and-filter-explained-with-examples/

归约归约冲突

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391025.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

为什么Java里面的静态方法不能是抽象的

为什么Java里面的静态方法不能是抽象的&#xff1f; 问题是为什么Java里面不能定义一个抽象的静态方法&#xff1f;例如&#xff1a; abstract class foo {abstract void bar( ); // <-- this is okabstract static void bar2(); //<-- this isnt why? }回答一 因为抽…

python16_day37【爬虫2】

一、异步非阻塞 1.自定义异步非阻塞 1 import socket2 import select3 4 class Request(object):5 def __init__(self,sock,func,url):6 self.sock sock7 self.func func8 self.url url9 10 def fileno(self): 11 return self.soc…

朴素贝叶斯实现分类_关于朴素贝叶斯分类及其实现的简短教程

朴素贝叶斯实现分类Naive Bayes classification is one of the most simple and popular algorithms in data mining or machine learning (Listed in the top 10 popular algorithms by CRC Press Reference [1]). The basic idea of the Naive Bayes classification is very …

python:改良廖雪峰的使用元类自定义ORM

概要本文仅仅是对廖雪峰老师的使用元类自定义ORM进行改进&#xff0c;并不是要创建一个ORM框架 编写fieldclass Field(object):def __init__(self, column_type,max_length,**kwargs):1&#xff0c;删除了参数name&#xff0c;field参数全部为定义字段类型相关参数&#xff0c;…

2019年度年中回顾总结_我的2019年回顾和我的2020年目标(包括数量和收入)

2019年度年中回顾总结In this post were going to take a look at how 2019 was for me (mostly professionally) and were also going to set some goals for 2020! &#x1f929; 在这篇文章中&#xff0c;我们将了解2019年对我来说(主要是职业)如何&#xff0c;我们还将为20…

在Java里重写equals和hashCode要注意什么问题

问题&#xff1a;在Java里重写equals和hashCode要注意什么问题 重写equals和hashCode有哪些问题或者陷阱需要注意&#xff1f; 回答一 理论&#xff08;对于语言律师或比较倾向于数学的人&#xff09;&#xff1a; equals() (javadoc) 必须定义为一个相等关系&#xff08;它…

vray阴天室内_阴天有话:第1部分

vray阴天室内When working with text data and NLP projects, word-frequency is often a useful feature to identify and look into. However, creating good visuals is often difficult because you don’t have a lot of options outside of bar charts. Lets face it; ba…

【codevs2497】 Acting Cute

这个题个人认为是我目前所做的最难的区间dp了&#xff0c;以前把环变成链的方法在这个题上并不能使用&#xff0c;因为那样可能存在重复计算 我第一遍想的时候就是直接把环变成链了&#xff0c;wa了5个点&#xff0c;然后仔细思考一下就发现了问题 比如这个样例 5 4 1 2 4 1 1 …

渐进式web应用程序_渐进式Web应用程序与加速的移动页面:有什么区别,哪种最适合您?

渐进式web应用程序Do you understand what PWAs and AMPs are, and which might be better for you? Lets have a look and find out.您了解什么是PWA和AMP&#xff0c;哪一种可能更适合您&#xff1f; 让我们看看并找出答案。 So many people own smartphones these days. T…

高光谱图像分类_高光谱图像分析-分类

高光谱图像分类初学者指南 (Beginner’s Guide) This article provides detailed implementation of different classification algorithms on Hyperspectral Images(HSI).本文提供了在高光谱图像(HSI)上不同分类算法的详细实现。 目录 (Table of Contents) Introduction to H…

在Java里如何给一个日期增加一天

在Java里如何给一个日期增加一天 我正在使用如下格式的日期: yyyy-mm-dd. 我怎么样可以给一个日期增加一天&#xff1f; 回答一 这样应该可以解决问题 String dt "2008-01-01"; // Start date SimpleDateFormat sdf new SimpleDateFormat("yyyy-MM-dd&q…

CentOS 7安装和部署Docker

版权声明&#xff1a;本文为博主原创文章&#xff0c;未经博主允许不得转载。 https://blog.csdn.net/u010046908/article/details/79553227 Docker 要求 CentOS 系统的内核版本高于 3.10 &#xff0c;查看本页面的前提条件来验证你的CentOS 版本是否支持 Docker 。通过 uname …

JavaScript字符串方法终极指南-拆分

The split() method separates an original string into an array of substrings, based on a separator string that you pass as input. The original string is not altered by split().split()方法根据您作为输入传递的separator字符串&#xff0c;将原始字符串分成子字符串…

机器人的动力学和动力学联系_通过机器学习了解幸福动力学(第2部分)

机器人的动力学和动力学联系Happiness is something we all aspire to, yet its key factors are still unclear.幸福是我们所有人都渴望的东西&#xff0c;但其关键因素仍不清楚。 Some would argue that wealth is the most important condition as it determines one’s li…

在Java里怎将字节数转换为我们可以读懂的格式?

问题&#xff1a;在Java里怎将字节数转换为我们可以读懂的格式&#xff1f; 在Java里怎将字节数转换为我们可以读懂的格式 像1024应该变成"1 Kb"&#xff0c;而1024*1024应该变成"1 Mb". 我很讨厌为每个项目都写一个工具方法。在Apache Commons有没有这…

ubuntu 16.04 安装mysql

2019独角兽企业重金招聘Python工程师标准>>> 1) 安装 sudo apt-get install mysql-server apt-get isntall mysql-client apt-get install libmysqlclient-dev 2) 验证 sudo netstat -tap | grep mysql 如果有 就代表已经安装成功。 3&#xff09;开启远程访问 1、 …

shell:多个文件按行合并

paste file1 file2 file3 > file4 file1内容为&#xff1a; 1 2 3 file2内容为&#xff1a; a b c file3内容为&#xff1a; read write add file4内容为&#xff1a; 1 a read 2 b write 3 c add 转载于:https://www.cnblogs.com/seaBiscuit0922/p/7728444.html

form子句语法错误_用示例语法解释SQL的子句

form子句语法错误HAVING gives the DBA or SQL-using programmer a way to filter the data aggregated by the GROUP BY clause so that the user gets a limited set of records to view.HAVING为DBA或使用SQL的程序员提供了一种过滤由GROUP BY子句聚合的数据的方法&#xff…

leetcode 1310. 子数组异或查询(位运算)

有一个正整数数组 arr&#xff0c;现给你一个对应的查询数组 queries&#xff0c;其中 queries[i] [Li, Ri]。 对于每个查询 i&#xff0c;请你计算从 Li 到 Ri 的 XOR 值&#xff08;即 arr[Li] xor arr[Li1] xor … xor arr[Ri]&#xff09;作为本次查询的结果。 并返回一…

大样品随机双盲测试_训练和测试样品生成

大样品随机双盲测试This post aims to explore a step-by-step approach to create a K-Nearest Neighbors Algorithm without the help of any third-party library. In practice, this Algorithm should be useful enough for us to classify our data whenever we have alre…