基于chrome开发人员工具的一个断点,我认为我正在处理我可以解决的范围问题.这是我定义函数的方式吗?下面的脚本是一个包含js文件和数组'timeStamp我想在其他函数中使用,而不必每次都调用我的loadData函数.
timeStamp数组在离开for循环之前一旦离开函数就变为未定义.
var timeStamp = []; // Want this array to be global
function loadData (url){
$.getJSON(url, function(json) {
for (var i=0;i<json.length;i++){
timeStamp.push(json[i].TimeStamp);
}
console.log(inputBITS); //returns the value
});
console.log(inputBITS); //undefined
}
Run Code Online (Sandbox Code Playgroud)
感谢您的任何帮助
看起来问题getJSON是异步的.当它执行并完成并且您的代码继续时,它仅指示网络操作的START以检索数据.实际的网络操作要到一段时间后才能完成.
完成后,将调用成功处理程序(指定为getJSON()调用的第二个参数)并填充timeStamp数组.只有在调用成功处理程序之后,timeStamp数组才有效.
因此,您不能timeStamp在紧跟getJSON()调用之后的代码中使用该数组(它尚未填充).如果其他代码需要timeStamp数组,则应该从成功处理程序调用该代码或使用其他一些计时机制来确保使用该timeStamp数组的代码在调用成功处理程序和timeStamp数组之后不会尝试使用它已经填充.
可以使一些Ajax调用是同步的而不是异步的,但这通常是一个非常糟糕的想法,因为它在整个网络操作期间锁定浏览器,这对于观看者来说是非常不友好的.修复编码逻辑以使用异步网络要好得多.
像这样的ajax调用的典型设计模式如下:
function loadData (url){
$.getJSON(url, function(json) {
// this will execute AFTER the ajax networking finishes
var timeStamp = [];
for (var i=0;i<json.length;i++) {
timeStamp.push(json[i].TimeStamp);
}
console.log(timeStamp);
// now call other functions that need timeStamp data
myOtherFunc(timeStamp);
});
// this will execute when the ajax networking has just been started
//
// timeStamp data is NOT valid here because
// the ajax call has not yet completed
// You can only use the ajax data inside the success handler function
// or in any functions that you call from there
}
Run Code Online (Sandbox Code Playgroud)