如何循环并将数组推入数组?

时间:2019-02-21 13:49:02

标签: javascript arrays

我正在尝试通过使用循环来简化代码

let tmpD = [];
let tmpS0 = [];
let tmpS1 = [];
let tmpS2 = [];

signed = doctors.doc(tmpD[0].key).collection('schedule').get();
signed.then(function(ss){
  ss.forEach(function(schedule){
    tmpS0.push(schedule.data());
  });
  console.log(tmpS0)
});
signed = doctors.doc(tmpD[1].key).collection('schedule').get();
signed.then(function(ss){
  ss.forEach(function(schedule){
    tmpS1.push(schedule.data());
  });
  console.log(tmpS1)
});
signed = doctors.doc(tmpD[2].key).collection('schedule').get();
signed.then(function(ss){
  ss.forEach(function(schedule){
    tmpS2.push(schedule.data());
  });
  console.log(tmpS2)
});

我尝试在第一个有符号的上方使用for(var i = 0; i < tmpD.length; i++)之类的for循环,并将数据推送到tmpS,事实证明,它将所有内容都推送到一个数组中。我还尝试将数组推送到tmpS[i],但它导致了错误。

1 个答案:

答案 0 :(得分:0)

您可以创建tmpS0tmpS1等的2D数组,并根据索引更新它们:

let tmpD = [];
let tmpS0 = [];
let tmpS1 = [];
let tmpS2 = [];

let tmps = [tmpS0, tmpS1, tmpS2];

tmpD.forEach(({ key }, i) => {
  const signed = doctors.doc(key).collection('schedule').get();
  signed.then(function(ss) {
    ss.forEach(function(schedule) {
      tmps[i].push(schedule.data());
    });
    console.log(tmps[i])
  });
})

更新

如果变量是动态的,则可以仅创建tmpS数组,并根据tmpD数组的索引继续向其推入:

let tmpD = [];
let tmpS = []; // 2D array

tmpD.forEach(({ key }, i) => {
  const signed = doctors.doc(key).collection('schedule').get();
  signed.then(function(ss) {
    tmpS[i] = tmpS[i] || []; // initialize the inner array

    ss.forEach(function(schedule) {
      tmpS[i].push(schedule.data());
    });

    console.log(tmpS[i])
  });
})

// tmpS will have same number of inner arrays as tmpD.length
console.log(tmpS)