数组在 reduce()、map() 等内部可用的原因是什么?

What is the reason array is available inside reduce(), map(), etc.?

在下面的示例中,我们可以访问数组 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);

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

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