1.reduce方法可用接收两个参数:
- //使用reduce实现filter方法
- const arr = ["March", "Jan", 6, 2, "A", "a"];
- //定义第二个参数的默认值为一个数组
- const newArr = arr.reduce((acc, cur, index) => {
- console.log(acc, cur, index);
- typeof cur === "string" && acc.push(cur);
- return acc;
- }, [333]);
- console.log(newArr);//[ 'March', 'Jan', 'A', 'a' ]
- //使用reduce实现数字的求和
- //第二个参数默认定义0 number类型
- const newArr2 = arr.reduce((acc, cur, index) => {
- typeof cur === "number" && (acc += cur);
- return acc;
- }, 0);
- console.log(newArr2);//8
-
运行结果如下图:
2.reduceRight :参数与使用方法和reduce一致,区别于reduce方法的只是它是从右往左执行的
- const arr = ["March", "Jan", 6, 2, "A", "a"];
- const newArr = arr.reduceRight((acc, cur, index) => {
- typeof cur === "string" && acc.push(cur);
- return acc;
- }, []);
- //这里打印之后可以看出,毕竟过滤了非字符串的参数,还将数组反转了
- console.log(newArr);//[ 'a', 'A', 'Jan', 'March' ]
如上图所示,当你想对一个数组进行反转加过滤等操作的时候,这个方法就完全突出了他的便携!