js中的reduce()函数讲解
2019-01-19 00:02
771 查看
定义:
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。对空数组是不会执行回调函数的。
案例
1.数组求和
// 1.数组求和 var arr = [1,5,8,6,15,78,65,25,48,55] var sum = arr.reduce(function(total,currentValue){ return total+currentValue; }); console.log(sum);//306 var eachSum = 0; arr.forEach(function(currentValue){ eachSum += currentValue; }) console.log(eachSum);//306
2.合并二维数组
//2.合并二维数组 var twoArr = [['mu','zi'],['dig','big'],['lucky','jiji']]; var oneArr = twoArr.reduce(function(total,currentValue){ // console.log(total) return total.concat(currentValue); }) console.log(oneArr);//["mu", "zi", "dig", "big", "lucky", "jiji"]
3.统计一个数组中有多少个不重复的单词:
//3.统计一个数组中有多少个不重复的单词: // 不用reduce时: var arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){ var obj = {}; for(var i= 0, l = arr.length; i< l; i++){ var item = arr[i]; obj[item] = (obj[item] +1 ) || 1; } return obj; } console.log(getWordCnt());//{apple: 2, orange: 3, pear: 1} // 用reduce时: var arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){ return arr.reduce(function(prev,next){ prev[next] = (prev[next] + 1) || 1; return prev; },{}); } console.log(getWordCnt());//{apple: 2, orange: 3, pear: 1}
4.对reduce的理解:
reduce(callback,initiaValue)会传入两个变量,回调函数(callback)和初始值(initiaValue)。
假设函数有个传入参数,prev和next,index和array。 Prev和next是你必须要了解的。
当没有传入初始值时,prev是从数组中第一个元素开始的,next是第二个函数。
但是当传入初始值(initiaValue)后,第一个prev将是initivalValue,next将是数组中的第一个元素。
比如:
// 4.对reduce的理解: var arr = ["apple","orange"]; function noPassValue(){ return arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); return prev; }); } function passValue(){ return arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); prev[next] = 1; return prev; },{}); } console.log("No Additional parameter:",noPassValue()); console.log("----------------"); console.log("With {} as an additional parameter:",passValue()); /* VM415673:4 prev: apple VM415673:5 next: orange VM415673:4 prev: apple VM415673:5 next: orange VM415673:19 No Additional parameter: apple VM415673:20 ---------------- VM415673:13 prev: {} VM415673:14 next: apple VM415673:13 prev: {apple: 1} VM415673:14 next: orange VM415673:21 With {} as an additional parameter: {apple: 1, orange: 1} */
若有不足请多多指教!希望给您带来帮助!
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接
您可能感兴趣的文章:
相关文章推荐
- js字符串方法replace()的第二个参数为函数讲解
- js 正则表达式之test函数讲解
- JS中的数组排序sort()和数组求和reduce()可接受函数做参数
- js 正则表达式之test函数讲解
- JS数组的reduce()函数用法
- js的reduce方法,改变头等函数
- JS学习笔记1——不要使用JavaScript内置的parseInt()和Number()函数,利用map和reduce操作实现一个string2int()函数
- JS的内建函数reduce
- JS高级函数--------map/reduce
- JS的内建函数reduce
- js 正则表达式之test函数讲解
- javascript-js 函数感悟讲解
- Array Map, Filter and Reduce in JS 牛x的讲解 in js
- JS的内建函数reduce
- 转译js数组的reduce函数为c#代码
- js的函数的按值传递参数(实例讲解)
- js prototype call 函数的讲解
- jquery中的ready函数和js中onload函数区别讲解
- JS的内建函数reduce
- js 正则表达式之test函数讲解