0

I am making an app that retrieves objects of Star Wars characters from the the Star Wars API. The characters are on 8 separate pages, so I want to push all of the character objects to one array that I can access globally. When I log charArray I have a full array of objects, however when I try to access the objects with bracket notation, it logs undefined. When I log the typeof(charArray) I get 'object'. Any help with this issue would be greatly appreciated!

$(document).ready(function() {
  let url = 'http://swapi.co/api/people/?page=';
  let charArray = [];

  getCharacters();
  makeCharacterList();


  function getCharacters() {
    for (var i = 1; i < 10; i++) {
      $.getJSON(url + i)
        .then(function(people) {
            let charResults = people.results;
            for (var i = 0; i < charResults.length; i++) {
              charArray.push(charResults[i]);
            }
          });
    }
  }

  function makeCharacterList() {
    console.log(charArray); //array of objects
    console.log(charArray[0]); //undefined
    console.log(typeof(charArray)); //object
  }
Alex
  • 3
  • 5
  • This is just the misleading effect of `console.log`: it only fetches the deeper content of a logged object at a later time, so really it *is* empty at the time of logging. This is because the ajax response only comes later, asynchronously. – trincot May 14 '17 at 20:46
  • Make an array of the request promises https://jsfiddle.net/3mft0Lr6/ and use `$.when` to run after all those requests have resolved – charlietfl May 14 '17 at 21:16

0 Answers0