0

So I have an array that I use .push() in a function to add to the array, but if I try to console.log the array outside of the function it shows the array as empty. I have the array declared as the very first line of code so every function can access it, but anything outside of the function I changed it in just shows the array as blank. Is there any way I can get the contents of the array from another function? Any help would be appreciated :)

I'm using JavaScript/jQuery if that helps at all.

Here's the code:

var id64List = [];

<other functions>

function handle(e) {
    if (e.keyCode === 13) {
        e.preventDefault();

        var searchBox = document.getElementById("search").value;

        var isnum = /^\d+$/.test(searchBox);

        if (searchBox.length == 17 && isnum === true) {
            useAPI();
        } else {
            alert("Not a valid steam url!");
        }
    }
}

    function useAPI() {
        var friendsRequest = new XMLHttpRequest();
            friendsRequest.open("GET", "<api im using>/friends/id64/" + id64);

            friendsRequest.onreadystatechange = function () {
                if (friendsRequest.readyState === 4) {

                    var friendsResponse = JSON.parse(friendsRequest.responseText);
                    var wrapperDiv = document.getElementById('friends-body');

                    var count = 0;

                    var friendFilter = 1;
                    var friendFilter2 = 0;

                    var arrayLength = friendsResponse.friendslist.friends.length;

                    for (var i = 0; i < arrayLength; i++) {

                        count++;

                        friendFilter = friendFilter + 2;
                        friendFilter2 = friendFilter2 + 2;

                        var friendDiv1 = document.createElement('div');
                        var friendDiv2 = document.createElement('div');

                        if (count < 9) {

                            friendDiv1.id = "friendDiv";
                            friendDiv1.innerHTML = "<div id='friendProfilePicture'></div>" + friendsResponse.friendslist.friends[friendFilter].steamid;
                            wrapperDiv.appendChild(friendDiv1);

                            id64List.push(friendsResponse.friendslist.friends[friendFilter].steamid);

                            friendDiv2.id = "friendDiv2";
                            friendDiv2.innerHTML = "<div id='friendProfilePicture'></div>" + friendsResponse.friendslist.friends[friendFilter2].steamid;
                            wrapperDiv.appendChild(friendDiv2);

                            id64List.push(friendsResponse.friendslist.friends[friendFilter2].steamid);

                        } else {

                            break;

                        }

                    }

                    document.body.appendChild(wrapperDiv);


                }
            };

            friendsRequest.send();

            alert(id64List);


    }

In the alert at the very bottom it just shows a blank space.

Connor S
  • 25
  • 7

2 Answers2

0

Update: after seeing your code I'd suggest checking out promises and reading this post on how to promisify your function. Javascript is single threaded meaning when code runs and it takes a long time (like a really long ajax request) it will block other code from running. This could cause things to be really really slow. So we have asynchronous functions to help. Asyncronous basically means you can make a call like this API call and while it's doing that other code can continue to run. So your program is more efficient. So what's happening here is you are making a call and before you even get to the point where you push into your array, alert() is running. So, you are logging the array before the push happens. Does this make sense? What you want is to complete your call and then call your alert function.

What you need to do is promisify your code.


This below is no longer relevant to your questions but I'll leave it here for you to check out scope as well because this is another important concept to understand.

Can you show your code in your question? It makes it easier to help you.

With out seeing, I'm imagining that you might be reassigning the array inside your function. If this is the case, you might want to google and read about scope. When you are inside a function you have local scope. If you declare an array with the same name it will actually be a different array.

var arr = []

function changeArr(){
   var arr = [];
   arr.push(1)
   console.log(arr) // arr will be [1]
}

changeArr();

console.log(arr) // arr will be []
Community
  • 1
  • 1
Turnipdabeets
  • 5,815
  • 8
  • 40
  • 63
  • I updated the post with my code. I'm pretty sure what you talked about is happening though, so how would I go about changing that? – Connor S Mar 02 '17 at 01:36
  • Of course the array will be empty, the function is never called – Falk Mar 02 '17 at 01:42
  • @Falk Sorry about that, forgot to show the other function when I call the useAPI function. It's just a short line of code where when I press enter in a textbox it calls the function. I'll edit my post and add that part though – Connor S Mar 02 '17 at 01:44
  • Cool, now you are calling the funct an the last console.log will no longer be empty. @ConnorS: I was referring to the example in the answer. In your code I assumed you called the function. – Falk Mar 02 '17 at 01:45
  • @Falk the last console log will still be empty because nothing was pushed into it. – Turnipdabeets Mar 02 '17 at 01:47
  • @Falk my code was already like that and it's still having that problem, I just didn't think to put it in this post – Connor S Mar 02 '17 at 01:47
  • @AnnaGarcia: how was there nothing pushed into it? Of course it was. The array is declared, the function is declared, the function is called and things get pushed into it. Then the log is called. Check this: https://jsfiddle.net/9sa1n3vv/ – Falk Mar 02 '17 at 01:49
  • @AnnaGarcia so how would I push to it to make it not empty? I was thinking I could have an invisible div that I set the inner HTML to the Array and then get the text using `.value` or something, but I figured there had to be a better way to do it so I went to here – Connor S Mar 02 '17 at 01:49
  • @ConnorS: your problem has to do with async calls in javascript. (see answer above) – Falk Mar 02 '17 at 01:50
  • @connerS I updated my answer to hopefully explain to you what is happening – Turnipdabeets Mar 02 '17 at 01:56
  • 1
    @falk this is not relevant to ConnorS's original question now but you are not looking close enough. Notice that the array inside the function is redeclared? The point there was to discuss scope. – Turnipdabeets Mar 02 '17 at 02:03
  • @Turnipdabeets You are right, I missed that. I apologize. – Falk Mar 02 '17 at 18:17
0

So the comments on your question were correct, you have an async issue at your hands.

Basically whenever you fire an AJAX call off, the program does that and then moves on. You fire your request and the program moves on to the alert Then it receives the answer to the request and assigns values to the array. (which you won't see because the alert got triggered before).

For your code to work, you have some options. You can either use a callback or a promise.

Here is some more reading material on the topic: http://cwbuecheler.com/web/tutorials/2013/javascript-callbacks/

Falk
  • 627
  • 5
  • 12