此代码是一个外部文件 test.js,它链接到 jQuery 文件后面的 index.html。 当我刷新浏览器并进入控制台时,我收到以下错误消息:
Uncaught TypeError: Cannot read property 'starshipName' of undefined
在第 20 行,我尝试提醒数组中第一项的 starshipName 属性。
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);
但是,当我输入最后一行代码或将 starships 数组记录到控制台时,它工作得很好。我很困惑为什么会发生这种情况,非常感谢任何帮助!预先感谢您。
最佳答案
$.getJSON
是一个异步函数。这意味着您的 alert()
在 starships
填充数据之前被调用 - 因此出现未定义的属性错误。
所有依赖于异步函数的操作都必须放置在回调中或从回调中调用。试试这个:
$.getJSON('https://swapi.co/api/starships/', function(data) {
starshipData(data);
// 1: place the call in the callback
// 2: always use console.log to debug as it does not coerce data types
console.log(starships[0].starshipName);
});
关于javascript - 意外的未捕获类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39332837/