首页 > 解决方案 > 正确读取数组

问题描述

我有一个名为“GuideDB”的 json 文件,其中包含有关某些东西的数据。

GuildDB.json
{"GuideID":{"prefix":"","DJ":null,"Roles":""}}

基本上我想以一种我可以管理该行中每个元素的方式访问数据“角色”,例如:

const myArray = GuildDB.Roles; //GuildDB.Roles is the only way to access that line.
myArray.forEach(element => { 
     console.log("<@&" + element + ">") 
});

此代码给出错误“forEach”,因为数组格式不正确。

如何在 GuildDB.Roles 中添加项目?

    client.database.guild.set(message.guild.id, {
      prefix: GuildDB.prefix,
      DJ: GuildDB.DJ,
      Roles: GuildDB.Roles + ", " + createdRole.id, //Bug: First run always writes the comma first.
    });

这将导致以下结果:

{"GuideID":{"prefix":"","DJ":null,"Roles":", 123, 1234, 12345, 123456"}}

这不是我想要的......而且我不在乎它的外观,我需要让读取/管理角色数据变得容易。

希望任何人都可以帮助..

标签: node.jsdiscord.js

解决方案


您可以执行类似的操作,先将 Roles 转换为数组,然后在其上使用 forEach 循环。

const myArray = GuildDB.Roles.split(",");


推荐阅读