-1

I can access the array words in global scope but when I try to find an item by typing words[index] , it returns undefined. How can I solve this?

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?
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

2

Yeah, You would get this error, because you are trying to read the index before it gets the data from the API.

So, basically you need to wait for the api to return the data and set the data in your variable words.

You can print the 3rd element in the console, by changing the place of your code

console.log(words[2])

Your code should be like this:

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();`   
Minal Shah
  • 1,402
  • 1
  • 5
  • 13