[英]reduce function in JavaScript and the accumulator object
I have a query in relation to the reduce function.我有一个关于减少 function 的查询。
The code is as follows:代码如下:
const marks = [60, 55, 80, 89, 90, 98, 75, 72, 50, 30, 20, 42]
const grade_count = marks.reduce(groupByGrade, {})
function groupByGrade (acc, mark) {
const {a = 0, b = 0, c = 0, d = 0, f = 0} = acc;
if (mark >= 90) {
return {...acc, a: a + 1};
}
if (mark >= 80) {
return {...acc, b: b + 1};
}
if (mark >= 70) {
return {...acc, c: c + 1};
}
if (mark >= 60) {
return {...acc, d: d + 1};
}
else {
return {...acc, f: f + 1};
}
}
console.log (marks)
console.log (grade_count)
console.log ('woo hoo')
My query is in relation to the following line where the accumulator is destructured for the first time:我的查询与以下行有关,其中累加器第一次被解构:
const {a = 0, b = 0, c = 0, d = 0, f = 0} = acc;
I wish to understand how come the properties on the accumulator object not get reset to zero on every iteration of the marks
array.我想了解累加器 object 上的属性为什么不会在
marks
数组的每次迭代中重置为零。
What am I missing here please?请问我在这里缺少什么?
I wish to understand how come the properties on the accumulator object not get reset to zero on every iteration of the marks array.
我想了解累加器 object 上的属性为什么不会在标记数组的每次迭代中重置为零。
Because the = 0
part of因为
= 0
部分
const {a = 0, b = 0, c = 0, d = 0, f = 0} = acc;
...is only used if the effective value of the property being destructured is undefined
("effective" = it's actually undefined
, or the property's not there at all). ...仅在被解构的属性的有效值
undefined
时使用(“有效”= 它实际上是undefined
的,或者该属性根本不存在)。
On subsequent calls to the reducer, acc
has non- undefined
values for those properties, so the default isn't used.在对 reducer 的后续调用中,
acc
对这些属性具有undefined
的值,因此不使用默认值。
Just as a side note, you could do the destructuring in the parameter list:顺便说一句,您可以在参数列表中进行解构:
function groupByGrade({a = 0, b = 0, c = 0, d = 0, f = 0}, mark) {
// ...
}
...although a
, b
, and the others wouldn't be constants anymore. ...虽然
a
, b
和其他人将不再是常数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.