无法弄清楚Discord Increments

Can't figure out Discord Increments

我想,一个巨大的 JavaScript 菜鸟,我不知道如何进行增量工作。

目前我的代码如下:

const Discord = require('discord.js')
const client = new Discord.Client()

client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
})

client.on('message', msg => {
if (msg.content === 'ping') {
    msg.reply('Pong!')
}

var i = 0;

if (msg.content === '+1') {
    msg.reply("Counter: " +i)
}
})

目前,当我在我的服务器中输入“+1”时,它只会说明 'i' 是什么。我想知道如何做到每次输入 +1,每次都会加起来。

有很多方法可以做到这一点。 这里有一些例子。

1.
if (msg.content === '+1') {
    i = i + 1
    msg.reply("Counter: " +i)
}

2.
if (msg.content === '+1') {
    i++
    msg.reply("Counter: " +i)
}

3.
if (msg.content === '+1') {
    ++i
    msg.reply("Counter: " +i)
}

每次消息回调触发时,您都将 i 的值重置为零。相反,您可以将 i 声明为全局变量,然后像这样在 if 语句中递增它:

var i = 0; // declare outside (to avoid resetting it)
client.on('message', msg => {
  if (msg.content === 'ping') {
      msg.reply('Pong!')
  }

  if (msg.content === '+1') {
      msg.reply("Counter: " +i)
      i++; // increment the value of i (same as i = i + 1)
  }
})