我正在 vue.js 中制作應用程式,現在我有一個小問題
async fetchCovidDataByDay(){
const res = await fetch(`https://api.covid19api.com/live/country/${this.name}/status/confirmed`);
const data = await res.json();
this.arrConfirmed= [];
this.arrDeaths = [];
this.arrRecovered = [];
this.arrActive = [];
data.forEach(item =>{
const date = moment(item.Date).format('MMMM Do YYYY');
const {
Confirmed,
Deaths,
Recovered,
Active
} = item;
this.arrConfirmed.push({date, total: Confirmed})
this.arrDeaths.push({date, total: Deaths})
this.arrRecovered.push({date, total: Recovered})
this.arrActive.push({date, total: Active})
})
return data;
},
所以我的總數應該是 Confirmed[i] - Confirmed[i-1] :)
uj5u.com熱心網友回復:
如果將 forEach 更改為
data.forEach((item, i) =>{
您可以像這樣訪問上一個專案
this.arrConfirmed.push({date, total: Confirmed - (data[i - 1]?.Confirmed || 0)})
?.Confirmed || 0純粹用于索引 0,當沒有前一項時
const data = [{Confirmed: 100}, {Confirmed: 120}, {Confirmed: 180}, {Confirmed: 300}];
const arrConfirmed= [];
let prevConfirmed = 0;
data.forEach((item, i) =>{
const { Confirmed, } = item;
arrConfirmed.push({total: Confirmed - (data[i - 1]?.Confirmed || 0)});
});
console.log(arrConfirmed);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/491820.html
標籤:javascript 数组 Vue.js
上一篇:迭代JavaScriptDOMTokenList時出現意外行為
下一篇:計算按鈕上的每個值
