雄辩的JavaScript第5章数组减少



我一直在试图弄清楚如何在reduce方法中将count定义为0,然后在函数中使用。有没有人可以逐步描述这段代码是如何工作的?谢谢!

let ranges = [[125184, 125259], [125264, 125274], [125278, 125280]];
console.log(
ranges.reduce((count, [from, to]) => {
return count + (to - from);
}, 0)
);

你用最后一个参数显式初始化它。 将该零更改为其他值,您将看到输出更改。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

一个简单的解释是,从(count, [from, to])开始的计数是一个累积值,我们将初始值定义为reduce方法的第二个参数

let initialValue = 0;//Or whatever value
console.log(
ranges.reduce((count, [from, to]) => {
return count + (to - from);
}, initialValue);

(;

let ranges = [[125184, 125259], [125264, 125274], [125278, 125280]];
console.log(
ranges.reduce((count, [from, to]) => {    // count gets 0 initially
console.log('count->', count, 'from->', from, 'to->', to)
return count + (to - from);
}, 0)              // passing initial value to count
);

因此,最初count获得 0 作为您传递的默认值。在此之后,初始调用计数将包含函数返回的任何内容(请参阅.reduce()内的日志(。

调用reduce()的数组是一个包含长度为 2 的arrayarray。所以,第二个参数是一个长度为二([from, to](的数组,因为.reduce()将逐个迭代它并得到那些内部数组。现在,这些数组将使用array destructuring assgnment进行解构,并将收集在fromto变量中。

因此,在第一次迭代时,您将内部数组的差值(to - from)添加到 0 并返回它。对于第二次迭代,您从第一次 (75( 返回的任何内容都将是count变量的值,依此类推。

您可以在此处阅读有关.reduce()的更多信息。

最新更新