_.reduce(list, iteratee, [memo], [context])
reduce方法把list中元素归结为一个单独的数值。
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里的参数比_.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);
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
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
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
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