JavaScript reduce对象数组返回对象 [英] JavaScript reduce returns object on Array of objects

查看:376
本文介绍了JavaScript reduce对象数组返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,假设 [{x:2,y:3},{x:5,y:4}] 我打电话给 reduce((c,n)=> cy + ny); 就可以了。它显然会返回 7

I have an array of objects, let's say [{x:2, y:3}, {x:5, y:4}] and i call reduce((c, n) => c.y + n.y); on it. It obviouslly returns 7.

但是,如果数组包含单个对象,那么假设 [{x:2,y:4}] 相同的reduce调用将返回对象本身 {x:2,y:4}

However, if the array contains a single object, let's say [{x:2, y:4}] the same reduce call will return the object itself {x:2, y:4}.

这是正常行为吗?我是否有义务检查结果是否为对象而不是之后的数字?

Is this normal behaviour? Am I obliged to check if the result is an object and not an number afterwards?

推荐答案

是的,这是正常行为 reduce 总是应该)时,$ c> 。您的代码在具有两个对象的数组之外的任何数组上都不会按预期工作。

Yes, this is the normal behaviour of reduce when you don't pass an initial value for the accumulator (which you always should). Your code doesn't work as expected on any arrays other than those with two objects.

Go for

arr.reduce((acc, el) => acc + el.y, 0)

这篇关于JavaScript reduce对象数组返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆