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

dk_*_*032 0 javascript arrays object multidimensional-array

我有一个对象数组作为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}
]
Run Code Online (Sandbox Code Playgroud)

我期待编写一个函数,在当前之前获取对象中所有'width'元素的总和.

就像是:

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

Gia*_*ris 5

为了更容易和更可重用的代码传递给方法的对象和索引,如下所示:

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

  return sum;
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

getAllBefore(obj, 5);
Run Code Online (Sandbox Code Playgroud)