javascript 何时使用reduce和reduce对吗?

ny6fqffe  于 2023-01-01  发布在  Java
关注(0)|答案(9)|浏览(191)

你能给我描述一下吗?

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

vatpfxk51#

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
e4eetjau

e4eetjau2#

在某些情况下,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)  )
pvcm50d1

pvcm50d13#

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>
*/
c8ib6hqw

c8ib6hqw4#

我错了一定要纠正我
我的理解是,仅仅在Array的背景下,reducereduceRight之间的根本区别--不仅仅是方向--在于在历史的先前时刻(在浏览器优化等之前),编译器将从10向后计数到0(arr.reduceRight - right-to-left),比从0向前数到10x 1 m8n1x快多了。
从右边开始减少意味着编译器可以从10开始,迭代器只能到达0,这意味着编译器在 * 每次 * 迭代时,必须检查当前迭代是否大于0
然而,当从左边(arr.reduce - left-to-right)开始减少时,集合的长度可能会改变,因此编译器必须在每次迭代时重新计算arr.length
举个例子,如果你有一个10的数组使用Array(10),而你使用了arr.reduce() - left-to-right,编译器必须检查以确保在reduce过程中没有其他东西被推送到集合上,以确定它在每次迭代中的位置。
希望这对某人有帮助:)

jfewjypa

jfewjypa5#

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

<!doctype html>
<html>

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

</html>

从左到右:12 = 23 = 6 * 4 = 24
右减示例

<!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

rm5edbpk

rm5edbpk6#

唯一的问题是计算顺序。Reduce执行“从左到右”,reduceRight执行“从右到左”。请参见以下示例:

<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>
jvidinwx

jvidinwx7#

从左到右减少工作。从右到左减少右工作。

var arr = ["1", "2", "3", "4", "5", "6"];
let total1 = arr.reduce(arrReduce);
let total2 = arr.reduceRight(arrReduce);
function arrReduce(prevValue, currentValue) {
    return prevValue + currentValue;
}
function reduceRight(prevValue, currentValue) {
    return prevValue + currentValue;
}
console.log(total1);//return 123456
console.log(total2);//return 654321
envsm3lx

envsm3lx8#

相反的顺序是很重要的,例如在Angular中处理HTTP拦截器时。然后你希望最后一个拦截器是链中第一个被执行的拦截器。我在GitHub上搜索了.reduceRight,发现总共有20个JS repos使用它。所以基本上,你可能不需要使用它。
https://medium.com/dev-proto/how-it-works-array-reduceright-f7dfbd32cc59

qncylg1j

qncylg1j9#

reduce()reduceRight()方法实用程序的使用是不同的,如以下代码所示,在大多数描述相同内容的页面中都会提到,

var arr = ["a", "b", "c", "d", "e"];

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

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

console.log(total1); // => abcde
console.log(total2); // => edcbe

使用这两种方法的目的不同,因为它取决于您正在使用的功能。
尝试思考一些现实世界的场景,但未能找到一个完美的例子。:)

相关问题