This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                            
                                (6个答案)
                            
                    
                    
                        How do I return the response from an asynchronous call?
                            
                                (38个答案)
                            
                    
                3年前关闭。
        

    

这段代码是一个外部文件test.js,该文件从jQuery文件后面的index.html链接到。
当我刷新浏览器并进入控制台时,出现以下错误消息:


  未捕获的TypeError:无法读取未定义的属性'starshipName'


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

10-08 03:47