为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript 算法仅显示 4 个月

Javascript 算法仅显示 4 个月

ITMISS 2024-01-18 16:46:56
我在显示一年中的正确月份时遇到问题。问题是几个月不互相跟进。我似乎无法正确理解算法。我现在遇到的问题是,这些月份不能正确地相互跟进。不应使用“Jan-Feb-Mar-Dec”,而应为“Dec-Jan-Feb-Mar”:这是我在这一点上的算法。当月份在不同年份重叠时,我无法理解如何按正确的顺序排列月份。新年的月份是数组开始的月份:   visibleMonths() {      let oldestMonth = 0;      this.months.forEach(month => {        if (month.visible && month.value > oldestMonth)          oldestMonth = month.value;      });      if (oldestMonth + 4 > 11) {          let visibleMonths = [];        // ORDER THE MONTHS       } else {        return this.months.filter(month => month.visible === true);      }    }months: [        { name: "Jan", value: 0, active: false, visible: false },        { name: "Feb", value: 1, active: false, visible: false },        { name: "Mar", value: 2, active: false, visible: false },        { name: "Apr", value: 3, active: false, visible: false },        { name: "Mei", value: 4, active: false, visible: false },        { name: "Jun", value: 5, active: false, visible: false },        { name: "jul", value: 6, active: false, visible: false },        { name: "Aug", value: 7, active: false, visible: false },        { name: "Sep", value: 8, active: false, visible: false },        { name: "Okt", value: 9, active: false, visible: false },        { name: "Nov", value: 10, active: false, visible: false },        { name: "Dec", value: 11, active: false, visible: false }      ],
查看完整描述

1 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

您可以简单地移动源数组并将其附加到临时数组,然后您可以slice:


const months = [

        { name: "Jan", value: 0, active: false, visible: false },

        { name: "Feb", value: 1, active: false, visible: false },

        { name: "Mar", value: 2, active: false, visible: false },

        { name: "Apr", value: 3, active: false, visible: false },

        { name: "Mei", value: 4, active: false, visible: false },

        { name: "Jun", value: 5, active: false, visible: false },

        { name: "jul", value: 6, active: false, visible: false },

        { name: "Aug", value: 7, active: false, visible: false },

        { name: "Sep", value: 8, active: false, visible: false },

        { name: "Okt", value: 9, active: false, visible: false },

        { name: "Nov", value: 10, active: false, visible: false },

        { name: "Dec", value: 11, active: false, visible: false }

      ]

const currentMonthIndex = new Date().getMonth()


function getVisibleMonths(months, currentMonthIndex) {

  const tmp = [...months]

  const res = []

  for (i = 0; i < currentMonthIndex; i++) {

    res.push(tmp.shift())

  }

  return [...tmp, ...res].slice(0, 4)

}


console.log(getVisibleMonths(months, currentMonthIndex))


查看完整回答
反对 回复 2024-01-18
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信