什么时候使用reduce和reduceRight?

Mr.*_*.AZ 22 javascript

你能帮我描述一下吗?

var arr, total;
arr = [1, 2, 3, 4, 5];
total = arr.reduce(function(previous, current) {
return previous + current;
});
// total is 15
Run Code Online (Sandbox Code Playgroud)

Har*_* He 46

reduce的顺序是从左到右,从右到左为reduceRight,如下面的代码所示:

var arr = ["1", "2", "3", "4", "5"];

total1 = arr.reduce(function(prev, cur) {
    return prev + cur;
});

total2 = arr.reduceRight(function(prev, cur) {
    return prev + cur;
});

console.log(total1); // => 12345
console.log(total2); // => 54321
Run Code Online (Sandbox Code Playgroud)

  • 很好的例子。 (3认同)

Qan*_*avy 12

在某些情况下,两者之间的差异reduce确实重要:reduceRight

但是,因为在JavaScript中添加两个整数是可交换的,所以在您的示例中无关紧要,就像在数学中如何1 + 2相等2 + 1.

var arr = ["A", "B", "C", "D", "E"];

console.log(  arr.reduce((previous, current)      => previous + current)  )
console.log(  arr.reduceRight((previous, current) => previous + current)  )
Run Code Online (Sandbox Code Playgroud)

  • 对不起,但我认为这是一个不好的例子,因为它不健壮,它只是一个不现实的例子.任何实现totalLeft或totalRight作为方法的人都会强制函数中的Number类型,这会使你的用例无关紧要. (5认同)

Dan*_*man 6

Array.reduceRight() 很棒的时候:

  • 您需要迭代一个项目数组来创建HTML
  • 并且在项目之前需要HTML中的计数器

.

var bands = {
    Beatles: [
        {name: "John", instruments: "Guitar"},
        {name: "Paul", instruments: "Guitar"},
        {name: "George", instruments: "Guitar"},
        {name: "Ringo", instruments: "Drums"}]
};
function listBandplayers(bandname, instrument) {
    var bandmembers = bands[bandname];
    var arr = [  "<B>" , 0 , ` of ${bandmembers.length} ${bandname} play ` , instrument , "</B>",
                "\n<UL>" , ...bandmembers , "\n</UL>" ];
    var countidx = 1;
    return arr.reduceRight((html, item, idx, _array) => {
            if (typeof item === 'object') {
                if (item.instruments.contains(instrument)) _array[countidx]++;
                item = `\n\t<LI data-instruments="${item.instruments}">` + item.name + "</LI>";
            }
            return item + html;
    });
}
console.log( listBandplayers('Beatles', 'Drums') );
/*
<B>1 of 4 Beatles play Drums</B>
<UL>
    <LI data-instruments="Guitar">John</LI>
    <LI data-instruments="Guitar">Paul</LI>
    <LI data-instruments="Guitar">George</LI>
    <LI data-instruments="Drums">Ringo</LI>
</UL>
*/
console.log( listBandplayers('Beatles', 'Guitar') );
/*
<B>3 of 4 Beatles play Guitar</B>
<UL>
    <LI data-instruments="Guitar">John</LI>
    <LI data-instruments="Guitar">Paul</LI>
    <LI data-instruments="Guitar">George</LI>
    <LI data-instruments="Drums">Ringo</LI>
</UL>
*/
Run Code Online (Sandbox Code Playgroud)

  • 我认为我花的时间比我理解“reduceRight”花的时间要长得多。 (7认同)