1 回答
![?](http://img1.sycdn.imooc.com/545864490001b5bd02200220-100-100.jpg)
TA贡献1817条经验 获得超6个赞
我认为你的目标是这样的:
// Mock data
const users = [
{ metadata: { creationTime: '3 apr' } },
{ metadata: { creationTime: '7 apr' } },
{ metadata: { creationTime: '26 jan' } },
{ metadata: { creationTime: '4 feb' } },
{ metadata: { creationTime: '9 dec' } },
{ metadata: { creationTime: '25 dec' } },
{ metadata: { creationTime: '9 apr' } }
]
// Months in lower-case... creationTime is assumed to also use lower-case
const months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
// Use `map` to create an array the same length as `months`
const counts = months.map(month => {
let count = 0
// Loop over the `users` array, note the use of `of`, not `in`
for (const user of users) {
// Using `includes` is somewhat crude but may work depending on how
// creationTime is formatted. It's no worse than indexOf
if (user.metadata.creationTime.includes(month)) {
++count
}
}
return count
})
console.log('Counts: ' + counts.join(' '))
在这种情况下,输出是一个包含每个月计数的数组,但您可以轻松地调整map函数内部的返回值以返回带有月份名称和计数的对象,如果这更容易使用的话。
正如我在评论中指出的,原始代码中的主要缺陷是使用for (var month in months) {. 这将迭代数字索引而不是月份名称,因此您只是检查0, 1, 2, etc.而不是jan, feb, mar, etc.. 要迭代数组的内容,您需要改用for/of循环。
添加回答
举报