歸約歸約沖突_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.pswp.cn/news/391025.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391025.shtml
英文地址,請注明出處:http://en.pswp.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…