Reputation: 39
I'm trying to make a discord bot for something, and I can't figure out why this is happening. In retrospect, this isn't really a big issue, but it would be a good idea to know the reasoning
Essentially, I have an array that looks something like this:
// Boosters.js
exports.test = ["Card", "Card2", "Card3", "Card4", "Card5",
"Card6", "Card7", "Card8", "Card9", "Card10"];
Then, in another file, I have a function:
// Functions.js
var pack = [];
let getCards = function getCards()
{
var obtainedCards = [];
for(i = 0; i < 7; i++)
{
var cards = Boosters.test[Math.floor(Math.random() * Boosters.test.length)];
obtainedCards.push(cards);
}
// Adds the cards from the obtained cards variable to the pack
pack.push(obtainedCards);
}
Then in a third file, I have a command that will call the function like so:
//
case "pack":
Functions.getCards();
message.channel.send("Cards obtained: " + Functions.pack.join(", "));
No issues here, it works. The problem is, in Discord it'll look like:
Cards obtained: Card1,Card5,Card2,Card6,Card2,Card1,Card7
Basically, it ignores the join() function. The weird thing is if I print the original test[], the bot actually spaces everything out using join(", "). So I don't know what the difference is.
Upvotes: 1
Views: 198
Reputation: 37045
This line is likely the culprit:
obtainedCards.push(cards);
To see why, consider this code:
let xs = [ 'x', 'y', 'z' ];
xs.push([ 'a', 'b', 'c' ]);
// xs is now:
// [ 'x', 'y', 'z', [ 'a', 'b', 'c' ] ]
//
// ... but you might have expected this:
// [ 'x', 'y', 'z', 'a', 'b', 'c' ]
If we join(', ')
this, the [ 'a', 'b', 'c' ]
element is converted to a string:
xs.join(', ') // "x, y, z, a,b,c"
Note the lack of spaces!
This behaviour occurs whenever an array is automatically converted to a string:
'xyz' + [ 'a', 'b', 'c' ] // "xyza,b,c"
To fix it, try this change:
obtainedCards = obtainedCards.concat(cards);
Upvotes: 1