使用moment.js
1.展示最近12个月的数据
let timeArr = [];//最近12个月的月份
for (let i = 0; i < 12; i++) {
timeArr.push(
`${moment(new Date()).subtract(i, "months").format("YYYY-MM")}`
);
}
timeArr.reverse();//时间排序
console.log(timeArr, "timeArr")
let arr = [] //模拟一个假数据
for (let i = 0; i < timeArr.length; i++) {
arr.push({ countName: timeArr[i], countVal: 0 })
//将真实数据塞进arr里面
for (let j = 0; j < data.length; j++) {
if (data[j].countName === timeArr[i]) {
arr[i] = { countName: data[j].countName, countVal: data[j].countVal }
}
}
}
2.展示最近七天的数据
let timeArr = [];
for (let i = 0; i < 7; i++) {
timeArr.push(
`${moment(new Date()).subtract(i, "days").day()}`
);
//周日换算为0 不是7
}
timeArr.reverse();
let arr = []
for (let i = 0; i < timeArr.length; i++) {
arr.push({ countName: Number(timeArr[i]), countVal: 0 })
for (let j = 0; j < data.length; j++) {
if (data[j].countName == timeArr[i]) {
arr[i] = { countName: data[j].countName, countVal: data[j].countVal }
}
}
}