簡體   English   中英

嘗試使用 for 循環對對象內的數組求和

[英]Trying to sum an array inside object with for loop

我有一個問題,我找不到該問題的答案,我想從points_sum points添加/求和所有值。

我試圖通過在對象中添加一個for循環來做到這一點,但后來我得到:

'意外的標記'

我怎樣才能以另一種方式做到這一點?

let sum = 0;
let teams = [
  team1 = {
    name: "Real",
    goal_plus: [3, 4, 2, 1],
    goal_minus: [1, 0, 2, 1],
    points: [3, 3, 3, 1],
    points_sum: for (let i = 0; i < points.length; i++) {
      sum += points[i];
    }
  },
  team2 = {
    name: "Barca",
    goal_plus: [5, 2, 5, 1],
    goal_minus: [1, 0, 0, 1],
    points: [3, 3, 3, 1],
    points_sum: 0
  }
]

您不能直接在對象內部添加for循環作為值,也不能在創建之前引用對象鍵或值,因此即使您可以添加for ,該部分:
i < points.length會拋出一個錯誤,比如"points is undefined" ,因為尚未創建對象,並且內存中也不存在點。

另一件事,數組鍵不能被命名,所以按鍵team1team2從陣列中移除,只有它們的價值將保持(對象),如果你想保持這些名稱,使可變teams的對象,而不是一個數組.

您的問題的解決方案可以是:創建一個接收數組並為您求和的函數,我在此函數中使用了.reduce()方法。

 let teams = [ { name: "Real", goal_plus: [3, 4, 2, 1], goal_minus: [1, 0, 2, 1], points: [3, 3, 3, 1], points_sum: SumPoints([3, 3, 3, 1]), }, { name: "Barca", goal_plus: [5, 2, 5, 1], goal_minus: [1, 0, 0, 1], points: [3, 3, 3, 1], points_sum: SumPoints([3, 3, 3, 1]) } ] function SumPoints(arr) { return arr.reduce((a, b) => a + b, 0) } console.log(teams)

解決此問題的另一種可能方法,如果您不能或不想將整個數組作為參數傳遞給外部函數,則讓points_sum空,然后在創建數組teams后,使用循環進行一些計算方法如forEach ,請參見以下代碼段:

 let teams = [{ name: "Real", goal_plus: [3, 4, 2, 1], goal_minus: [1, 0, 2, 1], points: [3, 3, 3, 1], points_sum: 0 }, { name: "Barca", goal_plus: [5, 2, 5, 1], goal_minus: [1, 0, 0, 1], points: [3, 3, 3, 1], points_sum: 0 } ] teams.forEach(x => { x.points_sum = x.points.reduce((a, b) => a + b, 0) }) console.log(teams)

暫無
暫無

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

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