[英]Passing parameters to reduce function
我讀過這篇文章,但我似乎沒有正確理解 JavaScript 的 reduce 語法。 如何將附加參數傳遞給自定義減速器 function?
調用減速機function。
data = Object.values(data.reduce(reducer, {}));
減速機 function 示例。
const reducer = (acc, cur) => {
if (somethingIsTrue) {
return acc;
}
};
現在它工作正常,但是假設我正在調用減速器 function 並且我想傳遞包含“Hello World”的簡單變量,function 沒有將其視為參數。 我怎樣才能做到這一點?
您可以執行 function 組合來“構建”稱為更高階 function 的東西。 基本上,這個想法是創建一個返回“子函數”的 function,它可以訪問父函數的變量。
// Parent function (getReducer)
function getReducer(stringToAppend) {
// Child function (reducer)
function reducer(acc, curr) {
// Child function has access to parent's variables (in this case stringToAppend)
acc[curr] = stringToAppend + curr
return acc
}
return reducer
}
const data = [0,1,2,3,4,5,6,7,8,9]
const result = data.reduce(getReducer("Hello World "), {})
console.log('result :>> ', result);
在控制台中:
result :>> {
'0': 'Hello World 0',
'1': 'Hello World 1',
'2': 'Hello World 2',
'3': 'Hello World 3',
'4': 'Hello World 4',
'5': 'Hello World 5',
'6': 'Hello World 6',
'7': 'Hello World 7',
'8': 'Hello World 8',
'9': 'Hello World 9'
}
我使用了function
語法,因為我發現它更詳細和明確地解釋了這一點。 您當然可以使用箭頭功能。 使用箭頭語法 function 看起來很簡單:
function getReducer (stringToAppend) {
return (acc, curr) => {
acc[curr] = stringToAppend + curr
return acc
}
}
看起來您想通過使用一個值(也可以是 function)來對數據進行分組。
例如,獲取由偶數個奇數分隔的所有值。
首先,您需要一個 function ,它返回一個標志來分隔值,例如
v => v % 2 // even -> 0, odd -> 1
然后拿一個減速機function,像
(acc, value) => {
// fn is not defined here, but it works a grouping function
// the following line reads:
// if acc[fn(value)] is undefined or null assign an empty array
// then push a value
(acc[fn(value)] ??= []).push(value);
return acc;
}
現在你需要通過在參數開始處添加一個閉包來組合fn
:
fn => (acc, value) => {
// rest is the same
最后調用 function
const evenOrOdd = v => v % 2, reducer = fn => (acc, value) => { (acc[fn(value)]??= []).push(value); return acc; }, data = [2, 7, 9, 4, 3, 5, 1], result = Object.values(data.reduce( reducer(evenOrOdd), {} )); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.