提问者:小点点

如何给变量JavaScript分配一个随机集字值?(Discord JS v12H


我正在尝试用我的discord机器人做一个猜谜游戏,当我输入“!猜谜游戏”时,它会反应出三个表情符号:1,2,3。然后它随机选择其中一个表情符号,并将其分配给变量“答案”。如果我点击与设置为“答案”变量的表情相对应的表情符号,它会说“恭喜你!你猜对了数字!”,如果不是,它会说“哦!祝你下次好运!”或者什么的。

这就是我的代码:

    if (msg.content === "!guessing game") {
        const filter = (reaction, user) => {
            return ['1️⃣', '2️⃣', '3️⃣'].includes(reaction.emoji.name) && user.id === msg.author.id;
        };
        msg.react('1️⃣');
        msg.react('2️⃣');
        msg.react('3️⃣');
        msg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
        .then(collected => {
        const reaction = collected.first();
        var num = Math.floor(Math.random() * 3) + 1;
        if (num === "1"){
            var answer = "1️⃣"
        }
        else{
            if (num === "2"){
                var answer = "2️⃣"
            }
            else{
                if (num === "3"){
                    var answer = "3️⃣"
                }
                else{
                   console.log("Random num failed")
          
                }
            }
        }
        if (reaction.emoji.name === answer) {
            msg.reply('You did it!');
        } 
        else{
            msg.reply('Better luck next time!');
        }
        


    })

当然,这就是我的控制台所说的:“随机数字失败了”我有一种感觉,选择一个随机的emoji,而不是一个随机的数字,然后把它转换成emoji,会更有效率。

有人知道怎么修吗?

(如果您能使它不区分大小写,我将非常感激,因为我似乎无法理解这一点。)


共2个答案

匿名用户

您应该在if(num===“1”)语句中使用==而不是===,或者删除数字-if(num===1)周围的双引号。这是因为===运算符更严格--它代表比较值和值的类型。Math.Random()函数返回Number类型的值,因此您正在比较NumberString:

console.log(3 == "3"); // will return true
console.log(3 === "3"); // will return false

更多信息请访问:https://developer.mozilla.org/en-us/docs/web/javascript/guide/expressions_and_operators

匿名用户

您还可以使用以下方法使代码更短:

const numbers = ['1️⃣','2️⃣','3️⃣'];
let randNum = numbers[Math.floor(Math.random() * numbers.length)];
// Output : '1️⃣' or '2️⃣' or '3️⃣' :)

相关问题