underscorejs-reduce學習

2.3 reduce

2.3.1 語法:

_.reduce(list, iteratee, [memo], [context])html

2.3.2 說明:

reduce方法把list中元素歸結爲一個單獨的數值。git

  • 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方法很使在拼接字符串的時候使用。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

相關文章
相關標籤/搜索