javascript - 函数中的项目未推送到数组
问题描述
我在应用程序中有一段代码难以将项目推送到空数组。在本节的开头,我创建了一些空数组变量。
var sumPOP = [];
var sumRACE = [];
var sumLANG = [];
var sumINCOME = [];
然后我将遍历一些选定的数据,所以我有一个for
循环。在这个循环中,我正在调用一个 api(我知道,它是 GIS。这无关紧要。只是假装它是一个 ajax 调用)来检索一些数据。我能够获取console.log()
数据并且它显示正确。然后我想将该数据(循环中的每个项目)推送到前面提到的空数组。然后为了测试数组是否已被填充,我console.log()
在循环内部和外部都设置了数组。我的问题是当我console.log
排列数组时没有任何显示。为什么数据没有被推到数组之外?注意:console.log(sumPOP) 在调用函数(esriRequest) 中运行确实显示了推送到数组的项目:
for (var i=0;i<results.features.length;i++){
...
esriRequest({
url:"https://api.census.gov/data/2016/acs/acs5",
content:{
get: 'NAME,B01003_001E,B02001_001E,B06007_001E,B06010_001E',
for: `tract:${ACS_TRCT}`,
in: [`state:${ACS_ST}`,`county:${ACS_CNTY}`]
},
handleAs:'json',
timeout:15000
}).then(function(resp){
result = resp[1];
POP = result[1];
console.log(POP);
sumPOP.push(POP);
RACE = result[2];
LANG = result[3];
INCOME = result[4];
console.log('POP: ' + POP + ', RACE: ' + RACE + ', LANG: '+ LANG + ', INCOME: ' + INCOME);
}, function(error){
alert("Data failed" + error.message);
});
console.log('POP: ' + sumPOP);
...
}
console.log('POP: ' + sumPOP);
附加信息:我的最终目标是在选定的数据经过迭代并汇总后得到最终的数组;或者更确切地说,将它们加在一起。我预期的数组结果是sumPOP = [143, 0, 29, 546, 99];
我想应用一个函数(也在循环之外)来做到这一点:
newSum = function(category) {
let nAn = n => isNaN(n) ? 0 : n; //control for nonNumbers
return category.reduce((a, b) => nAn(a) + nAn(b))
};
...然后运行popTotal = newSum(sumPOP);
以获取总数。
解决方案
我相信您的数据正在被推送,这似乎不是由于您console.log()
的
由于您正在处理异步 api 调用,因此保证您拥有数据的唯一地方是在您的.then()
函数内部。本质上,当您调试时,如果您在所有的console.log
's 处添加断点,您会注意到它会命中第一个外部的断点.then()
和最后一个内部的断点.then()
。由于这种排序,您的数组似乎没有将数据推送给它们。
我在下面的示例代码中添加了一些注释,以说明您应该在哪里看到数据。
编辑:我也做了一个小的调整,所以所有的数组都会被填充
编辑 2:修改代码,使其以“同步”方式处理多个异步承诺
var sumPOP = [];
var sumRACE = [];
var sumLANG = [];
var sumINCOME = [];
var myPromises = []; // added this new array for promise.all
for (var i = 0; i < results.features.length; i++) {
var myPromise = esriRequest({
url: "https://api.census.gov/data/2016/acs/acs5",
content: {
get: 'NAME,B01003_001E,B02001_001E,B06007_001E,B06010_001E',
for: `tract:${ACS_TRCT}`,
in: [`state:${ACS_ST}`, `county:${ACS_CNTY}`]
},
handleAs: 'json',
timeout: 15000
});
myPromises.push(myPromise);
// because you are making an async request, at this point, sumPOP may be empty
console.log('POP: ' + sumPOP);
}
Promise.all(myPromises).then(function(resp) {
result = resp[1];
POP = result[1];
console.log(POP); // this will show POP with data
RACE = result[2];
LANG = result[3];
INCOME = result[4];
sumPOP.push(POP);
sumRACE.push(RACE); // added this to populate array
sumLANG.push(LANG); // added this to populate array
sumINCOME.push(INCOME); // added this to populate array
// at this point, all your arrays should have data
console.log('POP: ' + POP + ', RACE: ' + RACE + ', LANG: ' + LANG + ', INCOME: ' + INCOME);
// now that this you have all values, you can call your outside function
this.handleData();
}, function(error) {
alert("Data failed" + error.message);
});
// because you are making an async request, at this point, sumPOP may be empty
console.log('POP: ' + sumPOP);
var handleData = function() {
// do something with the completed data
}
推荐阅读
- c++ - 如何在 SYCL 中实现重复的实时任务
- symfony - Symfony:如何设置一致的会话超时
- r - 如何使用反应数据框“锁定”缺失类别的颜色并在堆积条形图中包含缺失的 x 轴值?R 闪亮
- java - 测试 Java,分离测试类和主要方法 - 不使用 Junit
- ios - 在 Swift 框架中包含静态库
- django - 我应该如何“取消暂停”我暂停的 Heroku 应用程序?
- angular - 当我根据条件隐藏输入时,反应形式 Angular 10 未提交
- setuptools - python3 -m build ... 通过命令行参数提供版本号
- python - 从函数返回多个值的非侵入性方法?
- swift - 当敌人快速移动精灵套件时,游戏会冻结一秒钟