【发布时间】:2021-11-08 00:38:22
【问题描述】:
我无法访问数组中的特定对象。我将数据从 api 推送到数组。当我控制台日志国家Arr 它显示对象的所有属性的完整数组,但是当我尝试访问特定索引中的特定对象时,我得到未定义。此外,它应该返回一个数组,但 typeof 显示它是一个对象?有人可以帮忙吗?
const countriesURL = 'https://restcountries.eu/rest/v2/all';
let countriesArr = [];
async function getCountriesData() {
const response = await fetch(countriesURL);
const data = await response.json();
showCountries(data);
}
function showCountries(countries) {
countries.forEach((country) => {
countriesArr.push(country)
})}
console.log(countriesArr) //this shows array of objects
console.log(countriesArr[0]) //this shows undefined????
【问题讨论】:
-
您在哪里/何时调用您的函数?这看起来像是异步混淆,但在不知道实际调用顺序的情况下,几乎没有什么帮助
-
我在这里写的 showCountries 函数只是实际函数的一部分。 showCountries 在 dom 中显示数据,这很有效。同时我想创建一个包含所有数据的数组,这样我就可以对其进行排序或过滤。我在页面底部调用 getCountriesData(),在全局范围内
标签: javascript arrays object async-await