reduce (基础篇)讲到你会为止

2020-08-18  本文已影响0人  两朵小黑云

reduce()

照旧,先来MDN官方解释

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

栗子

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

reducer 函数接收4个参数:

   1 Accumulator (acc) (累计器)
   2 Current Value (cur) (当前值)
   3 Current Index (idx) (当前索引)
   4 Source Array (src) (源数组)

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

参数
callback
    执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:

    accumulator

        累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(见于下方)。
    currentValue
        数组中正在处理的元素。
    index 可选
        数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始。
    array 可选
        调用reduce()的数组

initialValue可选
    作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 
    在没有初始值的空数组上调用 reduce 将报错。 

返回值
    函数累计处理的结果

描述

reduce为数组中的每一个元素依次执行callback函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:

回调函数第一次执行时,accumulator 和currentValue的取值有两种情况:如果调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。

注意:如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。

ok 其实你现在还没太懂

上面的东西其实你可以从mdn找到,哈哈,but,重点来了!!!

reduce (实战篇)讲到你会为止

上一篇 下一篇

猜你喜欢

热点阅读