Okay guys so I've run into a problem on some code I've been working on. In the code below, I'm trying to console log the length of an array, but after printing to the console, I get an output of 0 for the array's length, and when I print the array itself, it shows that it is empty, but I can click the drop down arrow and see the element inside it.
// randomly selects card from array
export const selectCard = arr => {
const randomArr = Math.floor(Math.random() * arr.length);
console.log(arr.length);
console.log(arr);
}
Image of logged array length and empty array with an element inside.
To test what was happening, I decided to console log the array in a different function that is in the same file where the array is created. The array (blackCards
) is stored in an object.
let packArr = {
data: {},
packToUse: [],
whiteCards: [],
blackCards: [],
};
Console logging the array (blackCards
) in another function logs this:
const seperatePacks = (data) => {
// add white cards to array
packArr.whiteCards.push(data.whiteCards);
// add black cards to array
packArr.blackCards.push(data.blackCards);
// console log blackCards array
console.log(packArr.blackCards);
};
Here's a little more about how my code works. When a user clicks on a button, an event listener is activated, which calls other functions that eventually get json from a sever, then I add that data to the array, which you see in the code above. So now that you know how the code works, I can get to what is causing me to be even more confused. So, on the first click, I get the outcome of all the previous code and images combined, but if i click on the same button again, or click on a different one, I get the desired outcome (if I click on two button I get two elements in the array, so it's working correct). So, two or more clicks and the program works the way it should. Any help here would be great. Also sorry if this post was a little scuffed, it is my first one.
Here are the functions that eventually call selectCard
elements.packs.addEventListener("click", (e) => {
const packID = e.target.closest(".pack").id;
if (packID) {
packsToUse(packID);
// create black cards
blackCardDisplay(packArr.blackCards);
}
});
Above is the listener that was mentioned earlier, which calls the function below, that will call selectCard
.
export const blackCardDisplay = data => {
const card = `
<div class="cards card--black">
<h1 class="card--black-text card--text">${selectCard(data)}</h1>
</div>
`;
}
Here is the output after pressing two buttons. The array should contain two elements but in this case it only shows one. However when I expand the array, it shows a length of two instead of just one.
Console image of two button clicks
EDIT: After reading some of the comments I realized I forgot to mention that the contents of blackCards
is an array. So I have an array within an array.