我正在努力找出这里出了什么问题。我正在提取一些 json (是的,我知道我正在使用文本文件)。我在全局范围内有一个数组,我想将条目推送到其中,我正在迭代 json 并将其推送到该数组。只有当我注销时它是空的。这可能是愚蠢的事情,但我们将不胜感激任何帮助。
let charities = [];
fetch('../mapdata/markers.txt').then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Network response error.');
})
.then(charData => {
console.log(`inside: ${JSON.stringify(charData, null, 2)}`);
charData.map(entry => {
return charities.push(entry);
});
})
.catch(error => {
console.log('There has been a problem: ', error.message);
});
console.log(`outside: ${JSON.stringify(charities, null, 2)}`);
当它输入时,我认为这可能是一个异步问题......
最佳答案
您正在执行异步操作并在触发异步操作后读取 []。它将永远是空的。
相反,放入 console.log(outside: ${JSON.stringify(charities, null, 2)}
);一旦数据被插入数组,就在第二个 then() 内。
.then(charData => {
console.log(`inside: ${JSON.stringify(charData, null, 2)}`);
charData.map(entry => {
return charities.push(entry);
});
console.log(outside: ${JSON.stringify(charities, null, 2)});
})
关于javascript - fetch:将项目推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572871/