Javascript 从Fetch API在全局范围中未定义数组

Javascript 从Fetch API在全局范围中未定义数组,javascript,arrays,api,fetch,Javascript,Arrays,Api,Fetch,我可以访问全局范围中的数组“words”,但当我试图通过键入“words[index]”来查找项时,它返回未定义的。我怎样才能解决这个问题 let words = []; function fetchWords() { fetch("https://www.themealdb.com/api/json/v1/1/categories.php") .then((res) => res.json()) .then((data) =&g

我可以访问全局范围中的数组“words”,但当我试图通过键入“words[index]”来查找项时,它返回未定义的。我怎样才能解决这个问题

let words = [];

    function fetchWords() {
  fetch("https://www.themealdb.com/api/json/v1/1/categories.php")  
    .then((res) => res.json())   
    .then((data) => {  
      for (let i = 0; i < 13; i++) {   
        words.push(data.categories[i].strCategory);
      }
    });
}

fetchWords();`
console.log(words); //This works   
console.log(words[2]); // But this does not. Why?

是的,您会得到这个错误,因为您试图在索引从API获取数据之前读取它

因此,基本上您需要等待api返回数据并用变量字设置数据

通过更改代码的位置,可以在控制台中打印第三个元素

console.log(words[2])
您的代码应该如下所示:

let words = [];

function fetchWords() {
fetch("https://www.themealdb.com/api/json/v1/1/categories.php")  
.then((res) => res.json())   
.then((data) => {  
  for (let i = 0; i < 13; i++) {   
    words.push(data.categories[i].strCategory);
    console.log(words[2]);
  }
});
}

fetchWords();`