获取对象数组中所有指定元素的总和 [英] Get the sum of all specified elements in an array of objects
本文介绍了获取对象数组中所有指定元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组对象作为跟随者
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);
这篇关于获取对象数组中所有指定元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文