_.reduce(list, iteratee, [memo], [context])html
reduce方法把list中元素歸結爲一個單獨的數值。git
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方法很使在拼接字符串的時候使用。this
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/detailscode