Javascript 获取范围外的数据
我有一个小问题,我想返回一个函数为角度的数组。 我在匿名函数中处理数据,当我返回数组时,它是空的 我不知道怎么做Javascript 获取范围外的数据,javascript,angularjs,arrays,scope,Javascript,Angularjs,Arrays,Scope,我有一个小问题,我想返回一个函数为角度的数组。 我在匿名函数中处理数据,当我返回数组时,它是空的 我不知道怎么做 getCurrentExchangeTo : function(year, month, country){ var numberDayPerMonth = [ 31, 28, 31, 30, 31,
getCurrentExchangeTo : function(year, month, country){
var numberDayPerMonth = [
31,
28,
31,
30,
31,
30,
31,
30,
31,
30,
31,
30,
];
var vm = this;
this.country = country;
this.getCurrentExchangeFor = [];
var hello = "gello"
for(var i = 0; i < numberDayPerMonth.length; i++){
if((i + 1) === month){
for(let j = 1; j < numberDayPerMonth[i]; j++){
$http.get('http://api.fixer.io/' + year + '-0' + month + '-0' + j +'?symbols=' + vm.country).then(function (success) {
let countryDay = vm.country
vm.getCurrentExchangeFor[j] = success.data.rates[countryDay];
});
}
}
}
return vm.getCurrentExchangeFor
}
getCurrentExchangeTo:函数(年、月、国家){
var numberDayPerMonth=[
31,
28,
31,
30,
31,
30,
31,
30,
31,
30,
31,
30,
];
var vm=这个;
这个国家=国家;
this.getCurrentExchangeFor=[];
var hello=“gello”
对于(变量i=0;i
谢谢
编辑
使用promise,但它只返回一个数据
getCurrentExchangeTo : function(year, month, country){
var def = $q.defer();
var numberDayPerMonth = [
31,
28,
31,
30,
31,
30,
31,
30,
31,
30,
31,
30,
];
var vm = this;
this.country = country;
this.getCurrentExchangeFor = [];
var hello = "gello"
for(var i = 0; i < numberDayPerMonth.length; i++){
if((i + 1) === month){
for(let j = 1; j < numberDayPerMonth[i]; j++){
$http.get('http://api.fixer.io/' + year + '-0' + month + '-0' + j +'?symbols=' + vm.country).then(function (success) {
let countryDay = vm.country
vm.getCurrentExchangeFor[j] = success.data.rates[countryDay];
def.resolve(success.data.rates[countryDay])
});
}
}
}
return def.promise
}
getCurrentExchangeTo:函数(年、月、国家){
var def=$q.defer();
var numberDayPerMonth=[
31,
28,
31,
30,
31,
30,
31,
30,
31,
30,
31,
30,
];
var vm=这个;
这个国家=国家;
this.getCurrentExchangeFor=[];
var hello=“gello”
对于(变量i=0;i
您需要在此处使用promise,您返回的数组是空的,因为在填充数组之前就返回了该数组。
由于您有for循环和http调用,因此必须使用promise.all功能来确保在返回数组之前填充了所有数据。vm.getCurrentExchangeFor在异步的$http.get()中填充。在http调用成功之前,您正在返回数据。使用promise修复此问题您将获得空数组,因为
$http.get
是异步的,因此在填充之前会返回数据,但是。。因此,可能会调用$http.get()
调用,这会严重影响性能,理想情况下,应该在后端执行。。或者使用$q.all()
。如果我还想这样做,那么我现在还不知道承诺是什么。我测试了一个小教程,它工作了一半。函数只返回一个数据。这是因为它能够在返回语句getCurrentExchangeService.getCurrentExchangeTo(2015,2,'USD')时处理一个数据。然后(函数(数据){console.log(数据)})代码>我使用它重新扫描数据,但它返回一个随机数组长度