这个问题在这里已有答案:
我读过“提升”,“范围”和“回调”,但我仍然无法解决一个简单的问题。
首先,我在JavaScript中定义一个全局数组(在页面顶部):
var thefileNames = [];
我使用jQuery函数来获取文件夹的内容并将它们存储在这个数组中:
jQuery.get(order, function(data) {
$(data).find("a:contains(.txt)").each(function() {
thefileNames.push($(this).attr("href"));
console.log(thefileNames);
})
});
在控制台中,我将看到目录中每个文件的更新,直到我最后得到类似的东西(那里有3个文件):
File1.txt
File2.txt
File3.txt
所以信息显然在“thefileNames”中。但是,如果我在我的代码中使用其他任何地方并使用:
console.log(thefileNames);
我会得到这个结果:
[]
鉴于“thefileNames”是一个全局变量,我不明白这一点。一旦我离开jQuery函数,为什么值会被删除?
您正在以异步方式检索文件名,因此如果在代码中的某处放置console.log(thefileNames),则在执行日志时,您的thefileNames数组仍为空