【问题标题】:What is the reason array is available inside reduce(), map(), etc.?数组在 reduce()、map() 等内部可用的原因是什么?
【发布时间】:2021-09-22 07:41:06
【问题描述】:

在下面的示例中,我们可以通过numbersarr 访问数组。使用内部变量arr 似乎更符合函数式编程,但是我们应该使用它而不是外部变量的明确原因是什么,因为numbersarr 都是指向相同数组值的指针无论如何。

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, m, index, arr) => {
    console.log(`acc=${acc}, m=${m}, index=${index}, arr=${arr}`);
    console.log(`acc=${acc}, m=${m}, index=${index}, numbers=${numbers}`);
    return acc += m;
}, 100);
console.log(sum);

【问题讨论】:

  • 想象array.filter(.....).map(.....) ...在地图中,您想做一些涉及“过滤”数组的事情...您不能使用array
  • 它是回调的抽象和可重用性的更高形式。
  • 想象一下function foo(acc, m, index, arr) { ... }numbers.reduce(foo)...
  • @deceze 另一个例子function isUnique(x, index, arr) { /* ... */ } 然后用作arr.map(/* ... */).filter(isUnique)
  • 在 FP 中 reduce 被称为折叠,它只能访问累加器和当前值:foldr :: (a -> b -> b) -> b -> [a] -> b。但有时您需要一种更通用的机制来折叠复合值,幸运的是 FP 中还有其他递归方案:para :: (a -> [a] -> b -> b) -> b -> [a] -> b。我猜想通过它的两个附加参数减少实现相同目标的尝试。

标签: javascript functional-programming reduce


【解决方案1】:

因为不是每个数组都会存储在一个变量中。您可以链接对 map() 和其他的调用,或者在调用返回数组的函数之后,在这些情况下,您可以通过变量名访问数组。

functionThatReturnsAnArray(...).map((acc, m, index, arr) => {
    // We can only access the array because 
    //it was passed as an argument to the anonymous function
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 2017-06-27
    • 2013-02-16
    • 2021-09-01
    相关资源
    最近更新 更多