2.3 reduce
2.3.1 语法:
_.reduce(list, iteratee, [memo], [context])
2.3.2 说明:
reduce方法把list中元素归结为一个单独的数值。
- list可以为数组,对象,字符串和arguments
- iteratee 会传第四个参数(memo, element, index, list)或(memo, value, key, list)
- iteratee 需要有返回值
- memo是函数的初始值
- context可以改变iteratee内部的this
2.3.3 代码示例:
示例一:reduce可以操作数组和对象等集合
var sum1 = _.reduce(['1', '2', '3'], function (memo, element) {
return memo + element;
});
var sum2 = _.reduce({
a: 1,
b: 2,
c: 3
}, function (memo, element) {
return memo + element;
});
console.log(sum1); //=> String 123
console.log(sum2); //=> Number 6
示例二:iteratee的参数
iteratee里的参数比_.each和_.map多了一个memo。
如果外面没传memo,那么list的第一个值传为memo,并会少循环一次。
_.reduce([1, 2, 3], function (memo, element, index, list) {
//只有两次
console.log(memo, element, index, list);
//=> 1 2 1 [1, 2, 3]
//=> 3 3 2 [1, 2, 3]
return memo + element;
});
_.reduce([1, 2, 3], function (memo, element, index, list) {
//三次
console.log(memo, element, index, list);
//=> 0 1 0 [1, 2, 3]
//=> 1 2 1 [1, 2, 3]
//=> 3 3 2 [1, 2, 3]
return memo + element;
}, 0);
示例三:iteratee 需要有返回值
var result = _.reduce([1, 2, 3], function (memo, element, index, list) {
/*return*/ memo + element; //不要忘记return
}, 0);
console.log(result);
示例四:设置初始值
var result = _.reduce([1, 2, 3], function (memo, element) {
return memo + element;
}, 10);
console.log(result); //=> Number 16
示例五:context可以改变iteratee内部的this
var res = _.reduce([1, 2], function (memo, element) {
console.log(this);
//=> Object {no: 10}
//=> Object {no: 10}
return memo + element + this.no;
}, 0, {no : 10});
console.log(res); //=> Number 23
2.3.4 _.inject和_.foldl是_.reduce的别名。
inject:注入。
fold:折叠,foldl即fold left
var arr1 = _.inject([1, 2, 3], function (memo, element) {
return memo + element;
});
console.log(arr1); //=> Number 6
var arr2 = _.foldl([1, 2, 3], function (memo, element) {
return memo + element;
});
console.log(arr2); //=> Number 6
2.3.5 拼接字符串
reduce方法很使在拼接字符串的时候使用。
var data = [{name: 'iori'}, {name: 'kyo'}];
var html = _.reduce(data, function(memo, element){
return memo + '<p>' + element.name + '</p>';
}, ''); //这个空字符串一定要传
console.log(html); //=> <p>iori</p><p>kyo</p>
gitbook地址:https://www.gitbook.com/book/niec-fe/underscorejs/details