【问题标题】:JS matching strings from different arraysJS匹配来自不同数组的字符串
【发布时间】:2019-09-30 19:00:26
【问题描述】:

我正在使用 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)
    }
  }
})

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

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

【问题讨论】:

  • 目前尚不清楚您要做什么。你的预期输出是什么?你的输入是什么样的?
  • 我认为您的意思是 month of months 而不是 in。目前您正在迭代数字索引。我还要注意Jun 与其他月份的情况不同。也不清楚你为什么使用filter,似乎不太可能是合适的迭代器。
  • 我会避免使用 indexOf() 并将其替换为 include()。另外,我同意@skirtle。 for...of 更多地用于数组,for...in 更多地用于对象的键。 filter 旨在根据某些标准返回一些对象,看起来您并没有尝试这样做。你能提供更多的上下文吗?

标签: javascript firebase vue.js vuejs2


【解决方案1】:

我认为你的目标是这样的:

// 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 函数内的返回值,以返回一个带有月份名称和计数的对象,如果这样更容易使用的话.

正如我在 cmets 中指出的,您原始代码中的主要缺陷是使用了for (var month in months) {。这将遍历数字索引而不是月份名称,因此您只需检查0, 1, 2, etc. 而不是jan, feb, mar, etc.。要遍历数组的内容,您需要使用 for/of 循环。

【讨论】:

  • 哦!没有考虑到这一点!我会试试的..谢谢你!
  • 现在我学到了一些东西!我必须对数组使用for / of 循环:)
猜你喜欢
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2020-02-29
  • 2019-09-12
  • 2011-11-13
  • 1970-01-01
相关资源
最近更新 更多