JavaScript 减少对象数组上的 returns 个对象
JavaScript reduce returns object on Array of objects
我有一个对象数组,比方说 [{x:2, y:3}, {x:5, y:4}]
,我在其上调用 reduce((c, n) => c.y + n.y);
。显然 returns 7
.
但是,如果数组包含单个对象,假设 [{x:2, y:4}]
相同的 reduce 调用将 return 对象本身 {x:2, y:4}
。
这是正常行为吗?之后我是否有义务检查结果是否为对象而不是数字?
是的,当您不为累加器传递初始值时,这是 reduce
的正常行为(您 总是 应该)。除了具有两个对象的数组之外,您的代码在任何数组上都无法按预期工作。
争取
arr.reduce((acc, el) => acc + el.y, 0)
这是预期的行为,当您不提供初始值时(reduce
的第二个参数)。来自 MDN:
If the array is empty and no initialValue
was provided, TypeError
would be thrown. If the array has only one element (regardless of position) and no initialValue
was provided, or if initialValue
is provided but the array is empty, the solo value would be returned without calling callback
.
附带以下建议:
It is usually safer to provide an initial value because there are three possible outputs without initialValue
.
这样写:
reduce((c, n) => c.y + n.y, { y: 0 });
你有没有把累加器初始化为{ y : 0}
如果您没有,那么它将 return 原始对象。
let sum = data.reduce((c, n) => {
return { "y" : c.y + n.y };
}, { y : 0 });
这是因为 reduce 函数可以再接受 1 个参数 - 默认值,如果未指定它,它将接受数组的第一个值。这就是它适用于多个人的原因。
但是如果你这样做
let a = [{x:5, y:4}].reduce((c, n) => c + n.y, 0);
console.log(a)
求和得当。
注意:如果未提供 initialValue,reduce 将从索引 1 开始执行回调函数,跳过第一个索引。如果提供了 initialValue,它将从索引 0 开始。
如果数组为空且没有提供initialValue,会抛出TypeError。如果数组只有一个元素(不考虑位置)且没有提供initialValue,或者提供了initialValue但数组为空,则不调用回调直接返回solo值。
提供初始值通常更安全,因为在没有初始值的情况下有三种可能的输出,如下例所示。
我有一个对象数组,比方说 [{x:2, y:3}, {x:5, y:4}]
,我在其上调用 reduce((c, n) => c.y + n.y);
。显然 returns 7
.
但是,如果数组包含单个对象,假设 [{x:2, y:4}]
相同的 reduce 调用将 return 对象本身 {x:2, y:4}
。
这是正常行为吗?之后我是否有义务检查结果是否为对象而不是数字?
是的,当您不为累加器传递初始值时,这是 reduce
的正常行为(您 总是 应该)。除了具有两个对象的数组之外,您的代码在任何数组上都无法按预期工作。
争取
arr.reduce((acc, el) => acc + el.y, 0)
这是预期的行为,当您不提供初始值时(reduce
的第二个参数)。来自 MDN:
If the array is empty and no
initialValue
was provided,TypeError
would be thrown. If the array has only one element (regardless of position) and noinitialValue
was provided, or ifinitialValue
is provided but the array is empty, the solo value would be returned without callingcallback
.
附带以下建议:
It is usually safer to provide an initial value because there are three possible outputs without
initialValue
.
这样写:
reduce((c, n) => c.y + n.y, { y: 0 });
你有没有把累加器初始化为{ y : 0}
如果您没有,那么它将 return 原始对象。
let sum = data.reduce((c, n) => {
return { "y" : c.y + n.y };
}, { y : 0 });
这是因为 reduce 函数可以再接受 1 个参数 - 默认值,如果未指定它,它将接受数组的第一个值。这就是它适用于多个人的原因。
但是如果你这样做
let a = [{x:5, y:4}].reduce((c, n) => c + n.y, 0);
console.log(a)
求和得当。
注意:如果未提供 initialValue,reduce 将从索引 1 开始执行回调函数,跳过第一个索引。如果提供了 initialValue,它将从索引 0 开始。
如果数组为空且没有提供initialValue,会抛出TypeError。如果数组只有一个元素(不考虑位置)且没有提供initialValue,或者提供了initialValue但数组为空,则不调用回调直接返回solo值。
提供初始值通常更安全,因为在没有初始值的情况下有三种可能的输出,如下例所示。