【问题标题】:Day.js - Get array of remaining months in yearDay.js - 获取一年中剩余月份的数组
【发布时间】:2022-01-07 05:47:48
【问题描述】:

我想获得剩余月份的索引数组(0-index),不包括当前月份,倒计时,今年(或任何日期)。我正在使用lodashdayjs,但我觉得我的代码有点难以理解。

有没有更“dayjs”的方式来获得我想要的东西?我没有在文档的库或其他有类似问题的线程中找到更多帮助。

// All months - Current year's remaining months (0-index), we map in reverse until reaching 0
const yearRemainingMonths = map(range(11 - dayjs().month()), n => 11 - n)
// []

// Let's pretend we are in June, so we'd get
// [11, 10, 9, 8, 7]

【问题讨论】:

    标签: javascript dayjs


    【解决方案1】:

    没有什么更清洁的方法了。最后,您必须循环一次或存储预定义的数组。

    示例 1 - 缓存数据

    
    import dayjs from 'dayjs'
    
    const months = [0,1,2,3,4,5,6,7,8,9,10,11]
    function remainingMonths(month) {
      return [...months].splice(month+1).reverse()
    }
    
    console.log(remainingMonths(dayjs().month())) // []
    console.log(remainingMonths(5))  // june => [ 11,10,9,8,7,6]
    console.log(remainingMonths(0))  // [11,10,9,8,7,6,5,4,3,2,1]
    

    示例 2 - 使用 for loop

    function remainingMonths(month) {
      const remaining = []
      for(let i = 11; i > month; i--) {
        remaining.push(i)
      }
      return remaining
    }
    
    console.log(remainingMonths(11)) // []
    console.log(remainingMonths(5))  // june => [ 11,10,9,8,7,6]
    console.log(remainingMonths(0))  // [11,10,9,8,7,6,5,4,3,2,1]
    

    for 循环可能更干净一些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多