首页 > 解决方案 > 从 discord.js 中的 ana 数组中删除 args

问题描述

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

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 删除示例一样,消息被删除

标签: javascriptnode.jsarraysdiscord.js

解决方案


delete用于删除Object properties,因此它不适用于数组。您可以使用Array.prototype.splice()orArray 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 对您来说是理想的,因为它不会创建新数组,而是修改现有数组。希望这有帮助


推荐阅读