Javascript 当阵列在展开之前显示为空时,如何访问阵列
我试图用Javascript访问capitals数组中的数据,但我不能,因为当我发出警报或console.log时,它会给我未定义的数据。 我可以看到控制台中的所有数据,但无法使用索引访问它。Javascript 当阵列在展开之前显示为空时,如何访问阵列,javascript,arrays,Javascript,Arrays,我试图用Javascript访问capitals数组中的数据,但我不能,因为当我发出警报或console.log时,它会给我未定义的数据。 我可以看到控制台中的所有数据,但无法使用索引访问它。 问题在于fetch是一个异步函数,这意味着您的代码将启动它,但它将在完成之前移动到下一行代码。因此,当您使用console.log时,它只是还没有完成从链接的获取。您可以通过(不确定这是否是最佳解决方案)执行以下操作来克服此问题: var capitals = []; // Turn forEach
问题在于fetch是一个异步函数,这意味着您的代码将启动它,但它将在完成之前移动到下一行代码。因此,当您使用console.log时,它只是还没有完成从链接的获取。您可以通过(不确定这是否是最佳解决方案)执行以下操作来克服此问题:
var capitals = [];
// Turn forEach into for loop.
for(var item of countries) {
// "await" makes the code wait for it to finish to proceed
await fetch("https://restcountries.eu/rest/v2/alpha/"+item)
.then((resp) => resp.json())
.then(function(data){
capitals.push(data.capital);
})
.catch(function(error) {
console.log(error);
});
}
console.log(capitals);
我还没有测试过这段代码,所以它可能有效,也可能无效。试试看,如果问题仍然存在,我会看看我能做些什么。希望这有帮助!:) 获取方法是异步的。当您试图访问capitals数组时,它尚未完成。 移动此行:
// Changing capital[index] to capitals
Document.getElementById("result").innerHTML = capitals;
进入然后
块:
var capitals = []
countries.forEach(function (item, index) {
fetch("https://restcountries.eu/rest/v2/alpha/"+countries[index])
.then((resp) => resp.json())
.then(function(data){
capitals[index] = data.capital
document.getElementById("result").innerHTML = data.capital;
})
.catch(function(error) {
console.log(error);
});
});
console.log(capitals)
alert(capitals)
})
这回答了你的问题吗?尝试过了,但我得到了未捕获的SyntaxError:await仅在异步函数和顶级模块体中有效
var capitals = []
countries.forEach(function (item, index) {
fetch("https://restcountries.eu/rest/v2/alpha/"+countries[index])
.then((resp) => resp.json())
.then(function(data){
capitals[index] = data.capital
document.getElementById("result").innerHTML = data.capital;
})
.catch(function(error) {
console.log(error);
});
});
console.log(capitals)
alert(capitals)
})