简体   繁体   English

无法从对象数组中拼接一个项目

[英]Can't splice an item from an array of objects

I am writing a Discord bot, a part of which is an array of objects stored in JSON file.我正在编写一个 Discord 机器人,其中一部分是存储在 JSON 文件中的对象数组。 The user will be able to add and remove objects from the array with different commands.用户将能够使用不同的命令从数组中添加和删除对象。 Each object in the array has two properties: {"string":"test","count":0}数组中的每个对象都有两个属性: {"string":"test","count":0}

I have some code which successfully adds objects to the array:我有一些成功地将对象添加到数组的代码:

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);

I have also written some code which removes objects from the array:我还编写了一些从数组中删除对象的代码:

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 problem is, is that the code to add an object to this array works fine, however the code to remove objects doesn't.问题是,将对象添加到该数组的代码工作正常,但是删除对象的代码却没有。 When I send the command to remove an object, the bot replies with "the word " + args[3] + " has been successfully remove from your blacklist!"当我发送删除对象的命令时,机器人回复"the word ” + args[3] + “ has been successfully remove from your blacklist!" which makes me think the code is running successfully, but not actually working.这让我认为代码运行成功,但实际上并未运行。

In your code, removed was redeclared inside the for a loop.在您的代码中, removed是在 for 循环中重新声明的。

I have also added break so you don't need to traverse an entire array even after getting the result我还添加了 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!");
}

If you are using ES5, you can use filter function如果您使用的是 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!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM