簡體   English   中英

Day.js - 獲取一年中剩余月份的數組

[英]Day.js - Get array of remaining months in year

我想在倒計時、今年(或任何日期)中獲取剩余月份(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]

沒有什么更清潔的方法了。 最后,您必須循環一次或存儲預定義的數組。

示例 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循環更干凈一些。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM