簡體   English   中英

獲取對象數組中所有指定元素的總和

[英]Get the sum of all specified elements in an array of objects

我有以下對象的數組

[
    {"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}
]

我希望編寫一個函數,該函數在當前對象之前獲取對象中所有“寬度”元素的總和。

就像是:

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

為了使代碼更容易和更可重用,將對象和索引傳遞給方法,如下所示:

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

  return sum;
}

並這樣稱呼它:

getAllBefore(obj, 5);

這是一個使用切片首先返回正確長度的數組並使用a減少返回總和的示例

const getSum = (objNum, arr) => {
  const newArr =  arr.slice(0, objNum - 1)
  return newArr.reduce((current, next) => {
    return current + next.width;
  }, 0)
}

在ES5中

var getSum = (objNum, arr) => {
  vat newArr =  arr.slice(0, objNum - 1)
  return newArr.reduce(function(current, next) {
    return current + next.width;
  }, 0)
}

並在1行中

const getSum = (objNum, arr) => arr.slice(0, objNum - 1).reduce((current, next) =>  current + next.width, 0)

讓我們在JavaScript中使用reduce

 var arr = [ {"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} ]; console.log(arr.reduce((acc, b) => acc + b.width, 0.0)); 

如果您在不知道元素索引的情況下尋找解決方案,而只想發送對象,那么您將需要檢查當前項目的所有屬性以及可用的項目,您可以這樣進行:

var items = [
{"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}
];

function getAllBefore(current) {
    var sum = 0;

    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (current.width == item.width && current.height == item.height && current.X == item.X && current.Y == item.Y)
        {
             return sum;
        }

        sum += item.width;
    }
}

getAllBefore(items[2]);
function count(stack) {
    var totWidth = 0;
    stack.forEach(function(element) {
      totWidth = totWidth+element.width;
    });
  return totWidth;
}

工作實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM