如何遍历enmap?

时间:2018-12-10 13:57:11

标签: discord.js array.prototype.map for-of-loop

我正在尝试为我的discord.js机器人遍历enmap,我已经设法从单个条目中设置和获取值,但是我试图建立一个添加人员的命令像DM这样的新闻通讯,关于次要的重大更新。

if (args[0] === 'minor') {
  if (devlog.updates === 'minor') return message.channel.send('You are already recieving minor updates.').then(m => m.delete(5000))
  await client.devlog.set(userID, "yes", 'subscribed');
  await client.devlog.set(userID, "minor", 'updates');
  return message.channel.send('You will now recieve minor and major updates.').then(m => m.delete(5000))
}
if (args[0] === 'major') {
  if (devlog.updates === 'major') return message.channel.send('You are already recieving major updates.').then(m => m.delete(5000))
  await client.devlog.set(userID, "yes", 'subscribed');
  await client.devlog.set(userID, "major", 'updates');
  return message.channel.send('You will now recieve only major updates.').then(m => m.delete(5000))
}
if (!args[0]) {
  if (devlog.subscribed === 'yes') {
    await client.devlog.set(userID, "no", 'subscribed');
    await client.devlog.set(userID, "none", 'updates');
    return message.channel.send('You will stop recieving updates about RoboTurtle all together').then(m => m.delete(5000))
  }
  if (devlog.subscribed === 'no') {
    return message.channel.send(`Please choose wether you\'d like to recieve minor or major updates! (minor has both) **devlog minor/major**`).then(m => m.delete(10000))
  }
}

这是一种有效的方法,但是如果它们已经订阅了相同类型的更新,并且仅执行!devlog,它就不会触发消息,这意味着要么将它们设置为不接收更新,如果它们已经,或者告诉他们如果不是,请在两者之间进行选择,但是它只会以两种方式发送最后一条消息。

我尝试设置enmap迭代,以基于for...of相关文档的.map函数对所有订阅的人进行DM(因为它们只是“更高级”的地图) ),但无济于事,因为它们并没有真正显示不和谐风格的用例。

if (args[0] === 'minor') {
  for (let entry of client.devlog) {
    if (entry.updates === 'minor') {
      let user = client.users.get(entry)
      user.send(`**[Minor Update]\n${args.slice(1)}`)
    }
  }
}
if (args[0] === 'major') {
  for (let entry of client.devlog) {
    if (entry.subscribed === 'yes') {
      let user = client.users.get(entry)
      user.send(`**[Major Update!]\n${args.slice(1)}`)
    }
  }
}

万一有人想看完整的代码以更好地了解我在这里尝试做的事情:https://pastebin.com/bCML6EQ5

1 个答案:

答案 0 :(得分:0)

由于它们只是普通Map类的扩展,因此我将使用Map.forEach()遍历它们:

let yourEnmap = new Enmap();
yourEnmap.set('user_id', 'your_values');

yourEnmap.forEach((value, key, map) => {
  ...
});

在您的情况下,它将类似于:

client.devlog.forEach((values, user_id) => {
  // you can check your subscription here, the use the user_id to send the DM
  client.users.get(user_id).send("Your message.");
});