javascript中reduce的用法


一、reduce基本语法

  • reduce 函数的基本语法为:array.reduce(callbackfn, initialValue)
  • callbackfn 是回调函数,它接受四个参数:前一个值(prev)、当前值(current)、当前索引(index)和数组本身(array
  • initialValue 是初始值,可选参数。

二、reduce常用场景

1. 求和

简单数据求和的例子:

let arr = [1, 2, 3, 4, 5];
let res = arr.reduce((prev, next) => prev + next)
console.log(res); // 15

多维数组求和的例子:

let arr = [
  { count: 10, num: 3, name: '张三' },
  { count: 2, num: 22, name: '李四' },
  { count: 13, num: 5, name: '王五' },
  { count: 56, num: 4, name: '朱六' },
  { count: 33, num: 12, name: '赵二' }
];
let res = arr.reduce((prev, next) => prev + next.count * next.num, 0);
console.log(res); // 759

在这个例子里,reduce 函数对数组arr中的每个元素执行countnum相乘,然后将乘积加到前一个值prev中。由于初始值为 0,因此当遍历数组的第一个元素时,prev 的初始值为 0next.count * next.num 的值为 30,这两个值相加得到 30。接下来,prev 的值变为 30next.count * next.num 的值为 44,这两个值相加得到 74。以此类推,直到遍历完整个数组,得到最终的结果 759

2. 数据拼接

let keys = ['name', 'age'];
let values = ['张三', 18];
let res = keys.reduce((prev, next, index, arr) => (prev[next] = values[index], prev), {});
console.log(res); // {name: '张三', age: 18}

这段代码的作用是将两个数组keysvalues合并成一个对象。在reduce方法中,prev 参数的初始值为一个空对象 {},然后将keys数组中的每个元素依次作为next参数传入回调函数。在回调函数中,通过prev[next] = values[index]prev中对应的属性值设置为values数组中对应的元素值,最后返回prev对象。由于reduce方法会遍历整个keys数组,因此最终得到的对象包含了keys数组中的所有元素和它们对应的values数组中的元素。最终输出结果为 {name: '张三', age: 18}

三、实际项目中使用示例

1. 模拟Redux中的compose方法

Redux中的compose函数接受任意个函数作为参数,并返回一个新的函数。这个新的函数会将所有函数按照从右到左的顺序依次执行,并将前一个函数的返回值作为后一个函数的参数

1.1. 简单写法

  • 实现字符串的一些处理
  • 缺点: 如果有多个函数,那么调用非常麻烦。
function add(x, y) {
  return x + y;
};

function toUpper(str) {
  return str.toUpperCase();
};

function joint(str) {
  return `====${str}-----`
}
console.log(joint(toUpper(add('Hello', 'World')))); // ====HELLOWORLD-----

1.2 利用reduceRight写法

function add(x, y) {
  return x + y;
};

function toUpper(str) {
  return str.toUpperCase();
};

function joint(str) {
  return `====${str}-----`
}

function compose(...fns) {
  return function (...arguments) {
    let lastFn = fns.pop();
    return fns.reduceRight((prev, next) => {
      return next(prev);
    }, lastFn(...arguments));
  }
}

let res = compose(joint, toUpper, add)('Hello', 'World')
console.log(res); // ====HELLOWORLD-----

这段代码定义了三个函数(addtoUpperjoint)和一个高阶函数(compose)。add 函数接受两个参数并返回它们的和。toUpper 函数接受一个字符串并返回所有字母都大写的字符串。joint 函数接受一个字符串并将一些格式添加到它上面。

compose 函数接受任意数量的函数作为参数,并返回一个新函数,该函数以相反的顺序应用这些函数。在这个例子中,compose(joint, toUpper, add) 返回一个新函数,该函数首先将 'Hello''World' 作为参数传递给 add 函数,然后将 add 函数的结果作为参数传递给 toUpper 函数,最后将 toUpper 函数的结果作为参数传递给 joint 函数。最终结果是字符串 ====HELLOWORLD-----

1.3 利用reduce写法

function add(x, y) {
  return x + y;
};

function toUpper(str) {
  return str.toUpperCase();
};

function joint(str) {
  return `====${str}-----`
}

let compose = (...fns) => fns.reduce((prev, next) => (...arguments) => prev(next(...arguments)));

let res = compose(joint, toUpper, add)('Hello', 'World')
console.log(res); // ====HELLOWORLD-----

四、实现自己的reduce

Array.prototype.myReduce = function (callback, prev) {
  // 此处的this指的是传入的数组
  for (let i = 0; i < this.length; i++) {
    if (prev == undefined) {
      // this[i]:前一个值(prev)
      // this[i + 1]:当前值(current)
      // i + 1:当前索引(index)
      // this:数组本身(array)
      prev = callback(this[i], this[i + 1], i + 1, this);
      i++; // 每次迭代索引自增
    } else {
      prev = callback(prev, this[i], i, this);
    }
  };
  return prev; // 每次调用返回上一次的值
};

let res = [1, 2, 3].myReduce((prev, next, index, current) => {
  return prev + next;
});
console.log(res); // 6

这段代码实现了 myReduce 方法,该方法可以对数组中的每个元素进行迭代,并返回一个累加结果。方法接受两个参数:callbackprev,其中 callback 是回调函数,prev 是初始值,可选参数。

myReduce 方法遍历整个数组,并将数组中的每个元素依次作为 callback 的参数进行计算。在这个例子中,回调函数 (prev, next, index, current) => prev + next 的作用是将前一个值 prev 和当前值 next 相加,然后返回这个和。如果 prevundefined,则将前两个元素作为参数传入回调函数,否则将 prev 和当前元素作为参数传入回调函数。最终返回累加结果。

在这个例子中,数组 [1, 2, 3] 的所有元素进行了累加,得到结果 6

总结

本篇文章主要介绍了JavaScriptreduce方法的常用场景和使用示例,并提供了自己实现reduce方法的代码示例。掌握reduce方法的使用方法,能够提高代码的可读性和扩展性,减少冗余代码量,同时也实现了更好的代码复用。

  • 4
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

剑九_六千里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值