【问题标题】:Can't splice an item from an array of objects无法拼接对象数组中的项目
【发布时间】:2020-12-25 00:12:22
【问题描述】:

我正在编写一个 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!" 这让我认为代码运行成功,但实际上并没有工作。

【问题讨论】:

  • 但实际上不工作“不工作”是什么意思?
  • @Berto99 当我运行命令时,我检查了config.json 并且我应该删除的对象仍在文件中。
  • 可能你需要写回文件上的对象,不是吗?
  • 啊,是的,当然,谢谢。有时候我很傻xD

标签: javascript json discord.js javascript-objects


【解决方案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!");
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
  • 补充说明
【解决方案2】:

如果你使用的是 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!");
}

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 1970-01-01
    • 2017-06-11
    • 2021-06-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2016-07-12
    相关资源
    最近更新 更多