This code is an external file, test.js, which is linked to from index.html, after the jQuery file. When I refresh my browser and go into the console, I get this error message:
Uncaught TypeError: Cannot read property 'starshipName' of undefined
on line 20, where I try to alert the starshipName property of the first item in the array.
var starships = [];
function starship(starshipName, model, manufacturer) {
this.starshipName = starshipName;
this.model = model;
this.manufacturer = manufacturer;
}
function starshipData(data) {
for (i = 0; i < data.results.length; i++) {
var results = data.results[i];
starships.push(new starship(results["name"], results["model"], results["manufacturer"]));
}
}
$.getJSON('https://swapi.co/api/starships/', function(data) {
starshipData(data);
});
alert(starships[0].starshipName);
However, when I type out the last line of code or log the starships array to the console, it works perfectly. I am very confused as to why this is happening and will appreciate any help! Thank you in advance.