未捕获的类型错误

Unexpected Uncaught TypeError

本文关键字:类型 错误      更新时间:2023-09-26

这段代码是一个外部文件test.js,链接自index.html,位于jQuery文件之后。当我刷新浏览器并进入控制台时,我得到这个错误消息:

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