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

我正在使用 vuejs 开发一个 firebase 项目,试图绘制一个图表来显示每月的订阅者数量。主要问题是只计算每个月创建的配置文件的数量。其余的步骤对我来说没问题。


我想做这样的事情:


// calculation of number of users each month

let 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)

    }

  }

})

我是这样想象的,..但是控制台每个月都会打印重复的记录,..


我在想可能有另一种方式来做到这一点,..还是我只是坚持调整和尝试这个?


饮歌长啸
浏览 95回答 1
1回答

慕的地6264312

我认为你的目标是这样的:// Mock dataconst 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-caseconst 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循环。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript