无法计算出不和谐增量

时间:2019-03-04 07:10:55

标签: javascript increment discord

我就像一个巨大的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时,每次都会加起来。

2 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。 这是一些示例。

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

答案 1 :(得分:0)

每次触发邮件回调时,您都将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)
  }
})
相关问题