【问题标题】:remove args from ana array in discord.js从 discord.js 中的数组中删除 args
【发布时间】:2021-09-05 03:08:25
【问题描述】:

我想删除我之前使用命令添加到数组中的参数,我制作的代码:

const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const multipleArgs = args.slice(1).join(" ");

const banWordAdded = new Discord.MessageEmbed()
        .setColor('#42f59b')
        .setTitle("Ban word added:")
        .setFooter(multipleArgs)

const banWordRemoved = new Discord.MessageEmbed()
        .setColor('#42f59b')
        .setTitle("Ban word removed:")
        .setFooter(multipleArgs)

        if (banWords.some(word => message.content.toLowerCase().includes(word))) {
            message.delete()
            message.channel.send("Don't say that!");

    } else if (command === 'banword') {

        if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("You can't use this command")
        if (!args[0]) return message.channel.send("Choose either add or remove")
        
        if (args[0] == 'add')

        banWords.push(multipleArgs)
        message.channel.send(banWordAdded)
        console.log("Array updated");

    } else if (args[0] == 'remove') {

        delete banWords(multipleArgs)
        message.channel.send(banWordRemoved)
        console.log("Array updated")

添加禁止词时它工作得很好,但是当我想删除它时,机器人会删除包含禁止词的命令消息,而不是从 banWords 数组中删除它,就像我做 q!banword remove example 并且消息得到已删除

【问题讨论】:

    标签: javascript node.js arrays discord.js


    【解决方案1】:

    delete 用于删除Object properties,因此它不适用于数组。您可以使用Array.prototype.splice()Array filter()方法来完成此操作。

    方法一.splice()

    const indexOfWord = banWords.indexOf(multipleArgs); // finding the element in the arr
    if (indexOfWord == -1) return message.channel.send('word not found'); // if word isn't already in the array return
    banWords.splice(indexOfWord, 1); // removing the word
    // first parameter is the index of the element to remove, second one is the number of elements to remove.
    

    方法二.filter()

    const filteredArr = banWords.filter(x => x != multipleArgs); // filteredArr won't contain the words provided
    

    我相信 splice 对您来说是理想的选择,因为它不会创建新数组,而是修改现有数组。希望这有帮助

    【讨论】:

    • @TomTheItalianBBQ np :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2019-08-31
    • 2021-12-03
    • 1970-01-01
    • 2012-10-01
    • 2019-04-01
    • 2021-01-04
    相关资源
    最近更新 更多