获取对象数组中所有指定元素的总和

编程入门 行业动态 更新时间:2024-10-19 16:31:05
本文介绍了获取对象数组中所有指定元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一组对象作为跟随者

I have an array of objects as folllows

[ {"width":128.90663423245883,"height":160,"X":0,"Y":140}, {"width":277.0938568683375,"height":263,"X":128.90663423245883,"Y":37}, {"width":264.8267031014369,"height":261,"X":277.0938568683375,"Y":39}, {"width":229.14003389179788,"height":60,"X":264.8267031014369,"Y":240}, {"width":10.032771905968888,"height":177,"X":229.14003389179788,"Y":123} ]

我希望编写一个函数,该函数在当前对象之前获取对象中所有宽度"元素的总和.

I am looking to write a function that gets the sum of all 'width' elements in the object before the current.

类似的东西:

function getAllBefore(current) { // here i want to get the sum of the previous 4 'width' elements in the object } getAllBefore(obj[5]);

推荐答案

要获得更简单,更可重用的代码,请将对象和索引传递给该方法,如下所示:

For an easier and more reusable code pass to the method the object and the index, as follows:

function getAllBefore(obj, index){ var sum=0; for(var i=0; i<index; i++){ sum+=obj[i].width; } return sum; }

并这样称呼它:

getAllBefore(obj, 5);

更多推荐

获取对象数组中所有指定元素的总和

本文发布于:2023-10-24 20:00:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524863.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   组中   元素   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!