【问题标题】:Get item from array and delete it until the array is empty for Discord JS bot从数组中获取项目并将其删除,直到 Discord JS bot 的数组为空
【发布时间】:2021-10-15 05:22:53
【问题描述】:

我正在尝试用 JavaScript 制作一个不和谐的机器人。我正在尝试创建一个功能,每天在特定时间发送一个新问题(当天的问题)。

所有问题都以数组形式提供。我想让代码从数组中选择一个随机项目并将其发送到不和谐聊天中。它发送消息后,我想将其从数组中删除,使其无法再次选择问题。

我认为这很容易,但在 Google 的帮助下我无法弄清楚。

let scheduledMessage = new cron.CronJob('*/5 * * * * *', () => {
  const guild = client.guilds.cache.get('766724832334970942');
  const channel = guild.channels.cache.get('790532358574178314');

  let questions = ['Question A', 'Question B', 'Question B'];
  let questionsEmpty = [''];

  if (questions === '') {
    channel.send('Unfortunatly, there are no more questions')
  }
  else {
    let randomQuestionIndex = Math.floor(Math.random() * questions.length);
    channel.send(questions[randomQuestionIndex]);
    questions.splice(randomQuestionIndex, 1);
  }
}, null, true, 'Europe/Amsterdam');

这是我试图做的,但我显然不工作。

【问题讨论】:

  • 你说它不起作用,但你没有解释它的作用和预期。
  • if (questions === '') {?一个数组怎么可能等于一个空字符串?

标签: javascript arrays discord.js


【解决方案1】:

每次您的 cron 作业运行时,它都会重新创建问题数组,您需要将该数组声明为 在该函数之外

let questions = ['Question A', 'Question B', 'Question B'];
let scheduledMessage = new cron.CronJob('*/5 * * * * *', () => {
  const guild = client.guilds.cache.get('766724832334970942');
  const channel = guild.channels.cache.get('790532358574178314');

  if (questions.length === 0) {
    channel.send('Unfortunatly, there are no more questions')
  }
  else {
    let randomQuestionIndex = Math.floor(Math.random() * questions.length);
    channel.send(questions[randomQuestionIndex]);
    questions.splice(randomQuestionIndex, 1);
  }
}, null, true, 'Europe/Amsterdam');

【讨论】:

  • 我觉得自己很愚蠢......它完美无瑕。非常感谢!
猜你喜欢
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
相关资源
最近更新 更多