You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Day.js获取当年剩余月份(不含当月)0索引倒序数组的更优方案

实现方案

你可以完全依托 dayjs 原生的 .month() 方法获取月份索引,配合原生 JS 生成数组即可,不需要额外依赖 lodash,逻辑可读性更高,同时支持传入任意指定日期:

import dayjs from 'dayjs'

/**
 * 获取指定日期所属年份的剩余月份倒序0索引数组,不包含当前月
 * @param {dayjs.Dayjs} [date=dayjs()] 可选指定日期,默认取当前时间
 * @returns {number[]} 倒序剩余月份数组
 */
function getReverseRemainingMonths(date = dayjs()) {
  const currentMonth = date.month()
  // 长度为年末索引 - 当前月份索引,对应需要生成的元素数量
  return Array.from({ length: 11 - currentMonth }, (_, index) => 11 - index)
}

测试示例

// 模拟6月(0索引为5)
const juneDate = dayjs().month(5)
console.log(getReverseRemainingMonths(juneDate)) // 输出 [11, 10, 9, 8, 7]

// 模拟12月(0索引为11)
const decDate = dayjs().month(11)
console.log(getReverseRemainingMonths(decDate)) // 输出 []

方案优势

  • 仅用到 dayjs 官方暴露的标准 .month() API,属于原生支持的用法,没有额外黑盒逻辑
  • 去掉了 lodash 依赖,减少项目依赖体积
  • 逻辑直观易读,后续维护可以快速理解生成规则
  • 支持灵活指定任意日期,适配更多业务场景

内容的提问来源于stack exchange,提问作者Doge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:36:05