因此,我尝试使用XMLHttpRequest将数据传递给数组。看来我能够成功完成它,甚至可以表明该数组中包含元素,但是当我尝试访问某个元素或检查其长度时,它表示该数组为空。不知道为什么当它清楚地输出有效数组时会显示这些结果吗?
我尝试检查它是否实际上是一个数组,确保该数组在控制台日志中有效,并且还检查了for循环中的输出以查看是否工作正常。
var players_first
var players_last
var players_full
var players = []
for (var x = 1; x < 10; x++) {
var url = 'https://www.balldontlie.io/api/v1/players/' + x
let request = new XMLHttpRequest();
request.open('GET', url);
request.onreadystatechange = () => {
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
//console.log("Success");
players_first = JSON.parse(request.response).first_name;
players_last = JSON.parse(request.response).last_name;
players_full = players_first + " " + players_last;
console.log(players_full)
players.push(players_full);
}
};
request.send();
request.onerror = () => {
console.log("error")
};
}
console.log(players)
console.log(players.length)
console.log(players[0])
document.getElementById("mydiv").innerHTML = players
<div id="mydiv"></div>
实际输出:
Array(9)
0: "Alex Abrines"1: "Jaylen Adams"2: "Steven Adams"3: "Bam Adebayo"4: "DeVaughn Akoon-Purcell"5: "LaMarcus Aldridge"6: "Rawle Alkins"7: "Grayson Allen"8: "Jarrett Allen"length: 9__proto__: Array(0)
nbaAPI.js:37 0
nbaAPI.js:38 undefined
nbaAPI.js:24 Alex Abrines
nbaAPI.js:24 Jaylen Adams
nbaAPI.js:24 Steven Adams
nbaAPI.js:24 Bam Adebayo
nbaAPI.js:24 DeVaughn Akoon-Purcell
nbaAPI.js:24 LaMarcus Aldridge
nbaAPI.js:24 Rawle Alkins
nbaAPI.js:24 Grayson Allen
nbaAPI.js:24 Jarrett Allen
预期输出:
Array(9)
0: "Alex Abrines"1: "Jaylen Adams"2: "Steven Adams"3: "Bam Adebayo"4: "DeVaughn Akoon-Purcell"5: "LaMarcus Aldridge"6: "Rawle Alkins"7: "Grayson Allen"8: "Jarrett Allen"length: 9__proto__: Array(0)
nbaAPI.js:37 9
nbaAPI.js:38 Alex Abrines
nbaAPI.js:24 Alex Abrines
nbaAPI.js:24 Jaylen Adams
nbaAPI.js:24 Steven Adams
nbaAPI.js:24 Bam Adebayo
nbaAPI.js:24 DeVaughn Akoon-Purcell
nbaAPI.js:24 LaMarcus Aldridge
nbaAPI.js:24 Rawle Alkins
nbaAPI.js:24 Grayson Allen
nbaAPI.js:24 Jarrett Allen