reduce函数

reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。

对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。

<script>
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => {
console.log(accumulator +'|' + currentValue);
return accumulator + currentValue
};
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));//
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5)); //
</script>

输出如下:

语法:

callback 执行数组中每个值的函数,包含四个参数:

  • accumulator:累加器累加回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(如下所示)。
  • currentValue: 数组中正在处理的元素。
  • currentIndex: 可选,数组中正在处理的当前元素的索引。 如果提供了initialValue,则索引号为0,否则为索引为1。
  • array: 可选,调用reduce的数组。

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

用法如下

1.常见用法:

  var t = [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
console.log(accumulator + '|' + currentValue+ '-->' + currentIndex + '-->' + array);
return accumulator + currentValue;
});
console.log('t:', t);

输出如下:

2. 如果你提供一个初始值作为reduce方法的第二个参数,以下是运行过程及结果:

 var t = [0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
console.log(accumulator + '|' + currentValue+ '-->' + currentIndex + '-->' + array);
return accumulator + currentValue;
}, 10 );
console.log('t:', t);

输出如下:

3.将二维数组转化为一维

 var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(a, b) {
return a.concat(b);
},[]);
console.log(flattened);

 输出如下:

4.计算数组中每个元素出现的次数

 var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
console.log(allNames, '| ' + name);
if (name in allNames) {
allNames[name]++;
} else {
allNames[name] = 1;
}
return allNames;
}, {});
console.log(countedNames);

输出如下:

5.数组去重

let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result = arr.sort().reduce((init, current)=>{
if(init.length===0 || init[init.length-1]!==current){
init.push(current);
}
/*
注意:使用push的话,必须return 这个变量init,如果return init.push()的话会报错;
使用concat不存在这个问题,可以直接return a.concat(b);
*/ 
return init; }, []); console.log(result); //[1,2,3,4,5]

输出如下:

数组的方法之(Array.prototype.reduce() 方法)的更多相关文章

  1. 数组的方法之(Array.prototype.forEach() 方法)

    forEach() 方法对数组的每个元素执行一次提供的函数. 注意: 没有返回一个新数组 并且 没有返回值! 应用场景:为一些相同的元素,绑定事件处理器! const arr = ['a', 'b', ...

  2. 数组的方法之(Array.prototype.filter() 方法)

    filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素.     注意: filter() 不会对空数组进行检测.     注意: filter() 不会改变原始 ...

  3. 终于解决了IE8不支持数组的indexOf方法,array的IndexOf方法

    /* 终于解决了IE8不支持数组的indexOf方法 */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (el ...

  4. Array.prototype.reduce()

    reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值. arr.reduce([callback, initialValue]) c ...

  5. js Array​.prototype​.reduce()

    例子: , , , ]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 ...

  6. Array.prototype.reduce 的理解与实现

    Array.prototype.reduce 是 JavaScript 中比较实用的一个函数,但是很多人都没有使用过它,因为 reduce 能做的事情其实 forEach 或者 map 函数也能做,而 ...

  7. Array.prototype.map()方法详解

    Array.prototype.map() 1 语法 const new_array = arr.map(callback[, thisArg]) 2 简单栗子 let arr = [1, 5, 10 ...

  8. 利用Array Prototype的方法来实现对dom集合的筛选、indexOf、map等功能

    <!DOCTYPE html><html> <head> <title>TODO supply a title</title> <me ...

  9. [JavaScript] Array.prototype.reduce in JavaScript by example

    Let's take a closer look at using Javascript's built in Array reduce function. Reduce is deceptively ...

随机推荐

  1. Node中的模块系统

    加载require var 自定义变量名称 = require('模块') 两个作用: 执行被加载模块的代码 得到被加载模块中的exports导出接口对象 导出exports node中是模块作用域, ...

  2. DOS命令大全【转】

    见到网络上,觉得值得学习,特此收藏到这里,因为我几乎天天来这个网站 net use \\ip\ipc$ " " /user:" " 建立IPC空链接 net u ...

  3. java实践经验几种常见数据库连接池的使用比较

    经历的几个产品及项目中,包括了各种数据库及应用服务器,基本上几种常见的数据库连接池都用到了,根据使用的情况把这些连接池比较一下吧.(http://m.0834jl.com) 感觉在介绍之前有必要阐述一 ...

  4. MaxCompute安全管理指南-案例篇

    通过<MaxCompute安全管理-基础篇>了解到MaxCompute和DataWorks的相关安全模型.两个产品安全方面的关联,以及各种安全操作后,本篇主要给出一些安全管理案例,给安全管 ...

  5. 移动端,fixed bottom问题

    //不显示 .bar { position:fixed; bottom:0; z-index:99; } //显示 .bar{ position:fixed; bottom:calc(90vh); / ...

  6. DSP using MATLAB》Problem 8.16

    代码: %% ------------------------------------------------------------------------ %% Output Info about ...

  7. 分布式锁的Redis实现

    当我们开始开发项目部署运行时,项目规模不大,只是在一个JVM实例中运行,对同一资源的并发访问用JDK自带的锁机制就可以解决资源同时访问的问题.而随着项目的不断发展,单体应用已经无法满足日益增长的访问需 ...

  8. 我学习python没有记住的东西

    格式化 # 格式化 a=123 b='ww' print("%d,%s,%%"%(a,b)) # %d,%s,%f,%c,%f 格式化代码:print('{}{}'.format( ...

  9. line-height影响排版

    父级div设置了line-height值,子级div会继承line-height.如果不想子级元素继承,给子级元素设置line-height:normal.

  10. myeclipse中tomcat内存大小的设置

    刚刚安装了myeclipse9.0,又配置了tomcat7.0,想用ssh框架搭个项目试试tomcat7.0,没想到刚启动项目就会报错,在tomcat6.0中就不会有问题,上网查了那些都不起作用,后来 ...