gpt4 book ai didi

javascript - 什么时候使用reduce和reduceRight?

转载 作者:行者123 更新时间:2023-12-03 02:34:07 26 4
gpt4 key购买 nike

你能为我描述一下吗?

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

最佳答案

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

关于javascript - 什么时候使用reduce和reduceRight?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20753527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com