javascript - 从 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 删除示例一样,消息被删除
解决方案
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 对您来说是理想的,因为它不会创建新数组,而是修改现有数组。希望这有帮助
推荐阅读
- r - 使用 drc 包计算绝对 EC50 值时出现“NaNs 产生”警告
- java - 我不知道我在 java 中的结果集有什么问题
- for-loop - getPlayers 不在服务器端脚本上工作?
- linux - 使用 docker 应用程序在外部硬盘驱动器中创建新目录
- javascript - 我将如何使用 Promises 处理 Google 的 Recaptcha?
- python - 添加#noqa:F841后F841依然存在
- angular - Angular 8 网络工作者在 IE 中被破坏
- python - 在“pyenv/pyenv-virtualenv”中,我可以创建一个引用“system”的virtualenv,即之前没有“pyenv install”吗?
- angular - 如何在 mat-sidenav Angular 7 中引用正确的 routerlink?
- html - 我的 :hover 在 CSS 中只会影响我的 div/image