codecamp

Lodash _.reduce

_.reduce(collection, [iteratee=_.identity], [accumulator])

压缩 collection(集合)为一个值,通过 iteratee(迭代函数)遍历 collection(集合)中的每个元素,每次返回的值会作为下一次迭代使用(注:作为iteratee(迭代函数)的第一个参数使用)。 如果没有提供 accumulator,则 collection(集合)中的第一个元素作为初始值。(注:accumulator参数在第一次迭代的时候作为iteratee(迭代函数)第一个参数使用。) iteratee 调用4个参数:(accumulator, value, index|key, collection).lodash 中有许多方法是防止作为其他方法的迭代函数(注:即不能作为iteratee参数传递给其他方法),例如:_.reduce,_.reduceRight, 和_.transform。受保护的方法有(注:即这些方法不能使用_.reduce,_.reduceRight, 和_.transform作为 iteratee 迭代函数参数):

assign, defaults, defaultsDeep, includes, merge, orderBy, 和 sortBy

添加版本

0.1.0

参数

  1. collection (Array|Object): 用来迭代的集合。
  2. [iteratee=_.identity] (Function): 每次迭代调用的函数。
  3. [accumulator] (*): 初始值。

返回

(*): 返回累加后的值。

例子

_.reduce([1, 2], function(sum, n) {  return sum + n;}, 0);
// => 3 
_.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {  (result[value] || (result[value] = [])).push(key);  return result;}, {});
// => { '1': ['a', 'c'], '2': ['b'] } (无法保证遍历的顺序)


Lodash _.partition
Lodash _.reduceRight
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Lodash 简介

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }