我不知道我的代码有什么问题。这似乎是一个javascript问题。
我正在使用 $http.get 加载本地 txt 文件(有不同的方法吗?)。我想将此内容推送到一个数组中。为了进行测试,我只是推送任何字符串,以确保它与实际的 txt 文件无关。
var myArray = [];
$http.get(localFilePath).then(
function(success){
myArray.push("123");
},
function(error){
// other stuff
});
console.log(myArray);
此简单代码 不会生成正确的数组。如果我 console.log 创建了数组,这是来自 Chrome 开发工具的屏幕截图:
现在,这看起来像一个合适的数组,但它不是。如果我 console.log(myArray.length)
它返回 0。
使用相同的代码 myArray.push("123")
outside $http.get()
功能:
如果我在 $http.get() 函数中创建,有人能说出这两个数组之间有什么区别以及为什么第一个数组的创建方式不同吗?
最佳答案
这是一个异步问题。您在 promise 的“解决”函数之外调用 console.log()
。
var myArray = []
$http.get(localFilePath).then(function(result) {
myArray.push("123")
})
// outside resolve function
console.log(myArray)
由于这是一个异步操作,只有在 $http.get()
请求完成后(通常是几百毫秒后)才会调用 resolve 函数。但是,它不会等待,因此其余代码会继续运行。所以它启动 get()
,然后在 http 请求有机会完成之前立即运行 console.log()
,因此它没有填充数组在调用 console.log()
时。
如果将 console.log()
放入 resolve 函数中,您会看到数组已正确填充,因为它等待 http 请求完成,填充数组,并且只有然后它才打印出结果。
$http.get(localFilePath).then(function(result) {
myArray.push("123")
// inside resolve function
console.log(myArray)
})
关于javascript - AngularJs - $http.get() 中的 Array.push() 产生有缺陷的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54353047/