简体   繁体   中英

Array shows empty, but should have one element

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);
};

Image of logged array from a different function which is within the same file where the array is created and stored.

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.

So, after reading some comments I decided to implement @charlietfl's comment that maybe the array was console logged before the ajax call had been completed. Although this did not explicitly fix the problem, it set me on the right track to the solution.

Here is how I solved this problem:

I took the comments given about the console log completing before the ajax call could finish, and from there, I did some research and found this very simple article:

https://www.programmersought.com/article/26802083505/

In this article was an example using the setTimeout() method.

Here is the final solution to my problem.

export const selectCard = arr => {
    const randomArr = Math.floor(Math.random() * arr.length);

    setTimeout(() => {
        console.log(arr.length);
        console.log(arr)
    }, 1000);
}

Here is the output after adding the setTimeout() method on the first button press.

Image of solved array length and array console log

I'm not aware if this is the best solution for the problem, because I've seen some people disapprove of using this method in the past, but it will work fine for what I'm doing at this point. If anyone has a better way of solving this I would love to hear it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM