获取Array for Chartjs中的最近6个月的名称

时间:2020-04-18 11:27:12

标签: javascript arrays chatjs

我试图在图表js中动态获取最近六个月的名称作为标签

 var profitChart = {
    labels: ***** last six months name,
    datasets: [
      {
        label: "Profit",
        backgroundColor: "rgba(58,181,74,0.3)",
        borderColor: "rgba(58,181,74,0.80)",
        pointRadius: false,
        pointColor: "rgba(210, 214, 222, 1)",
        pointStrokeColor: "#c1c7d1",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: profitdata,
      },

1 个答案:

答案 0 :(得分:0)

创建一个具有月份的数组,使用日期对象的getMonth()获取当前月份,并使用Array.slice()提取最近6个月。

let months=["January","February","March","April","June", "July", "August", "September", "October", "November", "December"];
let currentMonth=new Date().getMonth()
var profitChart = {
        labels:months.slice(currentMonth-6).concat(months.slice(0,currentMonth)),
        datasets: [
          {
            label: "Profit",
            backgroundColor: "rgba(58,181,74,0.3)",
            borderColor: "rgba(58,181,74,0.80)",
            pointRadius: false,
            pointColor: "rgba(210, 214, 222, 1)",
        pointStrokeColor: "#c1c7d1",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: "profitdata",
      }]
      }
 console.log(profitChart)