为了账号安全,请及时绑定邮箱和手机立即绑定

JS 匹配来自不同数组的字符串

JS 匹配来自不同数组的字符串

饮歌长啸 2021-11-04 15:48:47
我正在使用 vuejs 开发一个 firebase 项目,试图绘制一个图表来显示每月的订阅者数量。主要问题是只计算每个月创建的配置文件的数量。其余的步骤对我来说没问题。我想做这样的事情:// calculation of number of users each monthlet months = ['jan', 'feb', 'mar', 'apr', 'may', 'Jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];this.users.filter(user => {  let print = user.metadata.creationTime;  for (var month in months) {    if (print.indexOf(month) > -1) {      console.log(user.email)    }  }})我是这样想象的,..但是控制台每个月都会打印重复的记录,..我在想可能有另一种方式来做到这一点,..还是我只是坚持调整和尝试这个?
查看完整描述

1 回答

?
慕的地6264312

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循环。


查看完整回答
反对 回复 2021-11-04
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信