gpt4 book ai didi

javascript - 如何访问 onreadystatechange 之外的数组(范围问题)

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:10 25 4
gpt4 key购买 nike

我有一个函数 ajaxCall() ,它调用一个内部有数组的 json 文档。我从 xmlhttp.responseText 返回的数据存储在数组 arrayImages 中。我需要在函数 ajaxCall() 之外访问数组 arrayImages,因为我需要该数组的长度 arrayImages.length。

function ajaxCall(){
xmlhttp.onreadystatechange = function(){

if(xmlhttp.readyState==4 && xmlhttp.status==200){
arrayImages = JSON.parse(xmlhttp.responseText);
output(arrayImages);

}
}

xmlhttp.open("GET", url, true);
xmlhttp.send();
}

我需要这样的功能

var arrayLength = arrayImages.length;

最佳答案

由于 onreadystatechange 是一个异步函数,因此您无法确定它何时返回您的数组。因此,处理它的唯一方法是使用回调函数在数组完成时输出数组的长度。像这样:

function ajaxCall(){
xmlhttp.onreadystatechange = function(){

if(xmlhttp.readyState==4 && xmlhttp.status==200){
arrayImages = JSON.parse(xmlhttp.responseText);
output(arrayImages);

}
}

xmlhttp.open("GET", url, true);
xmlhttp.send();
}

function output(array)
{
//your other stuff here
var arrayLength = array.length;
}

关于javascript - 如何访问 onreadystatechange 之外的数组(范围问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com