Marco Chavez
Marco Chavez

Reputation: 215

forEach returning a large number instead of the index

I am trying to create a bot in discord.js that adds a role to every user. I am running into an issue whenever I try to console.log the index, it gives me some weird large number instead of the index.

async execute(message) {
    const role = message.guild.roles.cache.find(r => r.name == 'Founder');

    if (!role) return message.channel.send(`**${message.author.username}**, role not found`);

    message.guild.members.cache.filter(m => !m.user.bot).forEach((member, i) => {
        member.roles.add(role);
        console.log(`Role was added to ${member.displayName}`);
        console.log(`${i} users completed`);
    });
    message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`);
}

Here is how it looks in the console.

Index is a strange number

Upvotes: 0

Views: 173

Answers (2)

Mineko Kayui
Mineko Kayui

Reputation: 761

Actually, you can save them all using JS's let identifier as such:

async execute(message) {
    const role = message.guild.roles.cache.find(r => r.name == 'Founder');
    if (!role) return message.channel.send(`**${message.author.username}**, role not found`);
    let amount = 0;
    message.guild.members.cache.filter(m => !m.user.bot).forEach(member => {
        member.roles.add(role);
        console.log(`Role was added to ${member.displayName}`);
        amount = amount + 1;
        console.log(`${amount} users completed`);
    });
    message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`);
}

Upvotes: 1

Rubydesic
Rubydesic

Reputation: 3476

If you look at the type signature of cache you will realize it is a "Collection" which extends Map. Therefore, the forEach method has a different signature, namely: forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;. The large numbers you are getting are the keys of the map, or the discord IDs.

You can convert it to an array first using .values() and then .forEach()

Upvotes: 4

Related Questions