_.reduceRight(list, iteratee, memo, [context])
reduceRight和reduce一样把list中元素归结为一个单独的数值,区别是reduceRight从list右边开始遍历。
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]
var flat = _.reduceRight('0123456789', function (a, b) {
return a.concat(b); //返回数组
}, []); //试试这里的数组不传会如何
console.log(flat); //= > ["9", "8", "7", "6", "5", "4", "3", "2", "1", "0"]
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>
_.reduceRight([1, 2], function (memo, element) {
console.log(this); //this已经不是null了
return memo + this;
}, '', null);
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