歸約歸約沖突
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/
歸約歸約沖突