我初始化了out
变量,以便它可以存储来自forEach循环的数据。我感到困惑的是,如果我要在循环中使用console.log(out)
,它可以正常工作,但是会重复打印出不必要的部分。但是,当我在数组外部使用console.log(out)
时,它将返回一个空数据(如最初初始化的数据)。我想在循环之外获取out
数据。我将如何解决该问题?预先感谢!
这是我的代码:
var myList = ["data1", "data2","data3", "data4"];
var out = " ";
myList.forEach(function(entry) {
var xmlhttp = new XMLHttpRequest();
var url = `https://www.URLGIVEN.com/${entry}/`
xmlhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
var arr = JSON.parse(this.responseText);
out += `SOMEDATA: ${arr.somedata}`;
// console.log(out); //WORKS but will print out more than necessary
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
});
console.log(out); //prints " " like when I initialized - it doesn't return anything back from the loop