when to use reduce and reduceRight?

前端 未结 6 2076
野性不改
野性不改 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 08:56

    ReduceRight is different from reduce method as it starts computation on values from right to left.

    Reference: http://www.thesstech.com/javascript/array_redcueright_method

    Reduce Example:

    
    
     
     
     
    
    

    Starting from left to right: 1*2 = 2*3 = 6 * 4 = 24

    Ref:http://www.thesstech.com/tryme?filename=javascript_array_reduce_method

    ReduceRight Example

    
    
     
     
     
    
    

    Starting from right to left: 1024/256 = 4/4 = 1

    Ref:http://www.thesstech.com/tryme?filename=javascript_array_reduceright_method

提交回复
热议问题