2017-07-16 174 views

回答

3

Date.prototype.toLocaleDateString()可以生成月份名称,因此可以生成12个项目的数组并将每个项目的索引(0 - 11)映射到月份名称。

const months = new Array(12).fill(0).map((_, i) => { 
 
    return new Date(`${i + 1}/1`).toLocaleDateString(undefined, {month: 'long'}) 
 
}); 
 
console.log(months);

上面的代码记录月份的数组:

[ 
    "January", 
    "February", 
    "March", 
    "April", 
    "May", 
    "June", 
    "July", 
    "August", 
    "September", 
    "October", 
    "November", 
    "December" 
] 

下面是它如何工作的:

  • new Array(12)初始化长度的新阵列12
  • 阵列不能被映射,直到它有某些项定义的,因此.fill(0)初始化所有项0
  • .map(...)映射所有12名0在数组
  • (_, i) => { ... }的是,忽略所述第一参数(这是一个功能项目本身,在每种情况下它将为0)并且仅使用索引,其将从011
  • new Date(`${i + 1}/1`)初始化具有MM/DD格式的日期的新日期对象,其中月份是1基于指数和月份的日子总是1。设置一天是必要的,因为否则它默认是今天的日期,如果碰巧是> 28这个月可能会滚动到下一个(例如,如果今天是7/31但是i == 2,那么日期将被初始化为2月31日,这是不存在的,所以Date对象只是在5月产生一天)
  • .toLocaleDateString(undefined, {month: 'long'})是魔法发生的地方。该对象包含一个formatMatcher对象,该对象控制将日期格式化为字符串时的格式。 month属性设置为'long',以便生成完整的月份名称(例如"July")。有趣的事实:第一个参数是未定义的,因此它不会覆盖用户的默认语言环境。这是因为真棒法国用户将自动看到法语月份名称:

["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]

如果你想保持英国的几个月里,只是将该参数设置为'en'


如果有帮助,这里的改写,使用旧JS语法相同的代码:

var months = []; 
 
for (var i = 0; i < 12; i++) { 
 
    var d = new Date((i + 1) + '/1'); 
 
    months.push(d.toLocaleDateString(undefined, {month: 'long'})); 
 
} 
 
console.log(months);

+0

Downvoter(S),请让我知道如果有什么我可以改进。 –

+3

你是否在发帖后5秒钟回答你自己的问题? –

+0

@zv_自从我在这里搜索这个问题/答案后,我同时询问/回答,但没有找到答案。我想出了自己的想法,并认为其他人可能对解决方案感兴趣。 –

0

我认为使用setMonth是更为有效和更容易比创建一个明白来自串接字符串的日期。

const months= []; 
 
const d = new Date(); 
 
for(let month = 0; month < 12; ++month) { 
 
    d.setMonth(month); 
 
    months.push(d.toLocaleString(undefined, {month: 'long'})); 
 
} 
 

 
console.log(months);

相关问题