when to use reduce and reduceRight?

前端 未结 6 2074
野性不改
野性不改 2020-12-17 08:44

Can you describe this for me?

var arr, total;
arr = [1, 2, 3, 4, 5];
total = arr.reduce(function(previous, current) {
return previous + current;
});
// total         


        
6条回答
  •  盖世英雄少女心
    2020-12-17 09:01

    Array.reduceRight() is great when:

    • you need to iterate over an Array of items to create HTML
    • AND need a counter in HTML prior to the items

    .

    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 = [  "" , 0 , ` of ${bandmembers.length} ${bandname} play ` , instrument , "",
                    "\n
      " , ...bandmembers , "\n
    " ]; var countidx = 1; return arr.reduceRight((html, item, idx, _array) => { if (typeof item === 'object') { if (item.instruments.contains(instrument)) _array[countidx]++; item = `\n\t
  • ` + item.name + "
  • "; } return item + html; }); } console.log( listBandplayers('Beatles', 'Drums') ); /* 1 of 4 Beatles play Drums
    • John
    • Paul
    • George
    • Ringo
    */ console.log( listBandplayers('Beatles', 'Guitar') ); /* 3 of 4 Beatles play Guitar
    • John
    • Paul
    • George
    • Ringo
    */

提交回复
热议问题