underscorejs-reduceRight学习

2.4 reduceRight

2.4.1 语法:

_.reduceRight(list, iteratee, memo, [context])

2.3.2 说明:

reduceRight和reduce一样把list中元素归结为一个单独的数值,区别是reduceRight从list右边开始遍历。

2.3.3 代码示例:

示例一:用reduceRight精简数组

var list = [
    [0, 1],
    [2, 3],
    [4, 5]
];

var flat = _.reduceRight(list, function (memo, element) {
    return memo.concat(element);
});

console.log(flat); //= > [4, 5, 2, 3, 0, 1]

示例二:list也可以字符串

var flat = _.reduceRight('0123456789', function (a, b) {
    return a.concat(b); //返回数组
}, []); //试试这里的数组不传会如何

console.log(flat); //= > ["9", "8", "7", "6", "5", "4", "3", "2", "1", "0"]

示例三:context可以改变iteratee内部的this

var data = [{name: 'iori'}, {name: 'kyo'}];
var context = {city : 'hangzhou'};

var html = _.reduceRight(data, function(memo, element){
    return memo + '<p>' + this.city + ':' + element.name + '</p>';
}, '', context);

console.log(html); //=> <p>hangzhou:kyo</p><p>hangzhou:iori</p>

2.3.4 context如果是null或undefined会是什么情况(坑)

_.reduceRight([1, 2], function (memo, element) {
    console.log(this); //this已经不是null了
    return memo + this;
}, '', null);

2.3.5 _.flodr是_.reduceRight的别名

var flat = _.foldr([[1], 2, 3], function (memo, element) {
    return memo.concat(element);
}, []);
console.log(flat); //=> [3, 2, 1]

gitbook地址:https://www.gitbook.com/book/niec-fe/underscorejs/details

你可能感兴趣的:(underscorejs-reduceRight学习)