JavaScript全局数组在jQuery get函数之外失去值[重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我读过“提升”,“范围”和“回调”,但我仍然无法解决一个简单的问题。

首先,我在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函数,为什么值会被删除?

javascript jquery arrays global-variables
1个回答
5
投票

您正在以异步方式检索文件名,因此如果在代码中的某处放置console.log(thefileNames),则在执行日志时,您的thefileNames数组仍为空

© www.soinside.com 2019 - 2024. All rights reserved.