什么时候使用reduce和reduceRight?

时间:2013-12-24 01:12:56

标签: javascript

你能为我描述一下吗?

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

7 个答案:

答案 0 :(得分:38)

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

答案 1 :(得分:11)

在某些情况下,reducereduceRight 之间的差异很重要:

但是,因为在JavaScript中添加两个整数是commutative,所以在您的示例中无关紧要,就像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)  )

答案 2 :(得分: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>
*/

答案 3 :(得分:3)

ReduceRight与reduce方法不同,因为它从右到左开始计算值。

参考:http://www.thesstech.com/javascript/array_redcueright_method

减少示例:

<!doctype html>
<html>
 <head>
 <script>
   var arr = [1,2,3];
   document.write(arr.reduce(function(x,y){return x*y;},4));
 </script>
 </head>
</html>

从左到右:1 * 2 = 2 * 3 = 6 * 4 = 24

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

ReduceRight示例

<!doctype html>
<html>
 <head>
 <script>
   var arr = [4,256];
   document.write(arr.reduceRight(function(x,y){return x/y;},1024));
 </script>
 </head>
</html>

从右到左:1024/256 = 4/4 = 1

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

答案 4 :(得分:2)

如果我错了,请纠正我;

我的理解是,仅在Array的上下文中,reducereduceRight之间的根本区别-不仅是方向-是在历史的先前时刻(之前浏览器优化等),编译器将从10倒数到0(arr.reduceRight - right-to-left),比从0倒数到10 {{1} }。

从右边减少意味着编译器可以从(arr.reduce - left-to-right)开始,而迭代器只能到达10。这意味着编译器在每个 迭代中必须检查 current 迭代是否大于0。容易。

但是,当从左侧的0开始减少时,集合的长度可能会发生变化,因此编译器必须在每次迭代时重新评估(arr.reduce - left-to-right)

例如,如果您使用arr.length10的数组,而您使用过Array(10),则编译器将必须进行检查以确保没有其他内容被压入在reduce期间进行收集,以确定其位置-在每次迭代中。

我希望这对某人有帮助:)

答案 5 :(得分:0)

唯一的是计算顺序。减少它&#39; 从左到右&#39 ;,reduceRight做到&#39; 从右到左&#39;。请参阅以下示例:

&#13;
&#13;
<html>

<head></head> 

<body> 

<script>

var a = [200, 100, 2];
var c = a.reduce(function(previousVal, currentVal){ 
previousVal = previousVal / currentVal; 
return previousVal;  
});
var c = a.reduceRight(function(previousVal, currentVal){ 
previousVal = previousVal / currentVal; 
return previousVal;  
});
alert(c);

</script> 

</body> 

</html> 
</html> 
&#13;
&#13;
&#13;

答案 6 :(得分:0)

相反的顺序很重要,例如在 Angular 中处理 HTTP 拦截器时。然后你希望最后一个拦截器成为链中第一个被执行的拦截器。我在 GitHub 上搜索了“.reduceRight”,发现总共有 20 个使用它的 JS 存储库。所以基本上,你可能不需要使用它。

https://medium.com/dev-proto/how-it-works-array-reduceright-f7dfbd32cc59