我正在编写一个Discord机器人,其中的一部分是存储在JSON文件中的对象数组。用户将能够使用不同的命令在阵列中添加和删除对象。数组中的每个对象都有两个属性:{"string":"test","count":0}
我有一些代码可以成功地将对象添加到数组中
let rawdata = fs.readFileSync('config.json');
let blacklist = JSON.parse(rawdata);
var newWord = {"string": args[3], "count": 0}
blacklist.words.push(newWord);
let data = JSON.stringify(blacklist);
fs.writeFileSync('config.json', data);
我还写了一些代码来从数组中删除对象:
var remove = false;
for (i = 0; i < blacklist.words.length; i++) {
if (blacklist.words[i].string === args[3]) {
blacklist.words.splice(i, 1);
var removed = true;
}
}
if (removed) {
message.reply(
"the word `" +
args[3] +
"` has been successfully remove from your blacklist!"
);
} else {
message.reply(
"I couldn't find the word `" + args[3] + "` on your blacklist!"
);
}
问题是,向该数组添加对象的代码运行良好,但是删除对象的代码却无法正常工作。当我发送删除对象的命令时,机器人会用"the word
“ + args [3] +” has been successfully remove from your blacklist!"
进行回复,这使我认为代码已成功运行,但实际上没有运行。
答案 0 :(得分:1)
在您的代码中,removed
在for循环内被重新声明。
我还添加了break,因此即使获得结果后您也无需遍历整个数组
var remove = false;
for (i = 0; i < blacklist.words.length; i++) {
if (blacklist.words[i].string === args[3]) {
blacklist.words.splice(i, 1);
removed = true;
break;
}
}
if (removed) {
message.reply("the word `" + args[3] + "` has been successfully remove from your blacklist!");
} else {
message.reply("I couldn't find the word `" + args[3] + "` on your blacklist!");
}
答案 1 :(得分:0)
如果您使用的是ES5,则可以使用过滤器功能
const filteredBlackList = blacklist.words.filter((item) => item.string !== args[3]);
var remove = false;
if (blacklist.words.length !== filteredBlackList.length) {
remove = true;
}
if (removed) {
message.reply("the word `" + args[3] + "` has been successfully remove from
your blacklist!");
} else {
message.reply("I couldn't find the word `" + args[3] + "` on your
blacklist!");
}