你能帮我描述一下吗?
var arr, total;
arr = [1, 2, 3, 4, 5];
total = arr.reduce(function(previous, current) {
return previous + current;
});
// total is 15
Run Code Online (Sandbox Code Playgroud)
Har*_* He 46
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
Run Code Online (Sandbox Code Playgroud)
Qan*_*avy 12
在某些情况下,两者之间的差异reduce和确实重要:reduceRight
但是,因为在JavaScript中添加两个整数是可交换的,所以在您的示例中无关紧要,就像在数学中如何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) )Run Code Online (Sandbox Code Playgroud)
Array.reduceRight() 很棒的时候:
.
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>
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9056 次 |
| 最近记录: |